2017-02-13 3 views
0

W3School의 수업을 이해하는 데 열심히 노력했지만 어떻게 든 작동하지 않습니다!알 수없는 코드 오류

여러분이 훨씬 잘 이해할 수 있도록 편집했습니다.

는 index.html 페이지입니다 :

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<h2>Get data as JSON from a PHP file on the server.</h2> 
 

 
<p id="demo"></p> 
 

 
<script> 
 
var myObj, i, x, j = ""; 
 
var xmlhttp = new XMLHttpRequest(); 
 

 
xmlhttp.onreadystatechange = function() { 
 
    if (this.readyState == 4 && this.status == 200) { 
 
\t \t myObj = JSON.stringify(this.response); 
 
     myObj1 = JSON.parse(myObj); 
 
\t \t document.getElementById("demo").innerHTML = myObj1.stuid; 
 
\t \t alert(myObj1); 
 
\t \t 
 
    } 
 
}; 
 

 
xmlhttp.open("GET", "sing.php", true); 
 
xmlhttp.send(); 
 

 
</script> 
 

 
</body> 
 
</html>

그리고 여기 sing.php 여기

<?php 
 

 
$servername = "localhost"; 
 
$username = "root"; 
 
$password = ""; 
 
$dbname = "sacapp"; 
 

 
// Create connection 
 
$conn = new mysqli($servername, $username, $password, $dbname); 
 
// Check connection 
 
if ($conn->connect_error) { 
 
    die("Connection failed: " . $conn->connect_error); 
 
} 
 
    
 
$result = $conn->query("SELECT stuid, stuname, stucourse, stustat, stulyear, stulog FROM stuinfo"); 
 
$outp = $result->fetch_all(MYSQLI_ASSOC); 
 

 
echo json_encode($outp); 
 
?>

와에게 다시입니다 sult of myObj1[{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"InfoTech","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"CivilEngi","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]

그러나 document.getElementById("demo").innerHTML = myObj1.stuid;Undefined 답만을 반환합니다. 여기서 무엇이 잘못 되었습니까?

나는 무엇이 잘못되었는지를 모른다. 누군가 실수를 지적 할 수 있습니까?

+4

'노래에서 마크 업을 제거하십시오.php' – Andreas

+3

나는 [w3fools] (http://www.w3fools.com/)의 팬이 아니다. – Nope

+0

아, 그걸 잊어 버렸지 만, 그게 그냥 정의되지 않았다. – Arkonsol

답변

-1

업데이트 답변.

좋아요, 모든 것을 확인하고 로컬 설정이 있습니다. 코드에는 많은 실수가 있습니다.

index.html을 살펴 보겠습니다.

이렇게 표시됩니다. (당신이 실수를 어디 의견을 추가했습니다.) 'sing.php'에 관해서는

<!DOCTYPE html> 
<html> 
<body> 

<h2>Get data as JSON from a PHP file on the server.</h2> 

<p id="demo"></p> 

<script> 
var myObj, i, x, j = ""; 
var xmlhttp = new XMLHttpRequest(); 

xmlhttp.onreadystatechange = function() { 
    console.log(this); 
    if (this.readyState == 4 && this.status == 200) { 

     myObj = JSON.parse(this.response); //**IT'S 'response' NOT 'responseText' To look at the object data, you can do console.log(myObj) and see what the object looks like. in the developer window** 

     document.getElementById("demo").innerHTML = myObj.student_id; //**YOU DON'T HAVE A PROPERTY 'id' BUT YOU DO HAVE 'student_id', again look at the json object in the developer window. ** 
    } 
}; 

xmlhttp.open("GET", "sing.php", true); 
xmlhttp.send(); 
</script> 
</body> 
</html> 

, 당신의 데이터베이스를 가지고 있지 않기 때문에 나는이 생각하기 때문에 내가 그들을 병합 할 수 있도록, 나는 내 자신의 배열을 생성 당신이하려는 일.

<?php 

$outp = array(
    'student_id' => '10-00000', 
    'student_name' => 'Breaker M. North', 
    'student_course' => 'BSIT', 
    'student_stat' => 0, 
    'student_log' => 1 
); 

$outp2 = array(
    "stu_log" => 2, 
    "course_name" => "IT 202", 
    "student_id" => "10-00000" 
); 

echo json_encode(array_merge($outp, $outp2)); 

?> 

당신은 echo json_encode($outp + $outp2); 당신이 실제로 생성하고 새로운 배열과 별도의 값으로 $outp$outp2을 옮기고 작업을 수행 할 때. 그래서 당신은 []을 가졌고, 당신은 두 가지 가치뿐만 아니라 하나를 가졌습니다. undefined은 속성에 액세스 할 수 없기 때문에 대신 json 배열의 첫 번째 요소에 액세스합니다.

참고로 JOIN on student_id ...을 사용하여 SQL 요청을 하나만 만들 수 있지만 이는 질문의 일부가 아닙니다.

+0

아니요. 전례없는 결과입니다. 3 – Arkonsol

+0

@Arkonsol이 방금 전 답변을 업데이트했습니다. 3 가지 주요 오류를 발견하고 작동하지 않는 이유를 설명했습니다. –

+0

예,하지만 그 이후로 나는 그것을 객체로 원합니다. 나는 괄호를 맞춰야하는 것이 환영받지 못하는 이유를 알고 있습니다. 그래서 그것은 정의되어 있지 않습니다.하지만 계속해서 그 객체를 지우려고합니다. – Arkonsol

0

sing.php에서 html을 제거하고 JSON 만 반환합니다. 브라우저에서 올바른 출력을 볼 수는 있지만 원본을 보면 등 태그를 볼 수 있습니다. 스크립트가 오류를보고 실패하고 있습니다.

+0

그걸로 실험했지만 그때 그것은 단지 정의되지 않은 말합니다 :/ – Arkonsol

0

그것은 AJAX 요청이 HTML을 반환처럼,이에 코드를 변경, 경고를 사용하여 반환되는 있는지 확인할 수 있습니다 보인다 : 당신은 있는지 확인해야

if (this.readyState == 4 && this.status == 200) { 
    alert(xmlhttp.responseText); 
} 

를 HTML이 경고에있는 경우 sing.php 페이지의 경로가 올바른지 확인하십시오 :

xmlhttp.open("GET", "sing.php", true); 
+0

그것은 지금 나는 html과 body 태그를 삭제했지만 올바른 정의를 가지고 있습니다. – Arkonsol