2014-04-29 2 views
0

PHP 스크립트에서 반환 한 XML 파일을 Javascript로 구문 분석하려고하는데 무언가가 작동하지 않고 무엇을 모르겠습니다. PHP의는 다음과 같습니다는 XML 반환 Javascript XML 구문 분석 오류

<?php 
    header("Content-Type: text/xml"); 
    include ('database_connection.php'); 

    // Start XML file, create parent node 
    $dom = new DOMDocument("1.0"); 
    $node = $dom->createElement("elements"); 
    $parnode = $dom->appendChild($node); 


    $category = $_GET['category']; 
    $city = $_GET['city']; 
    $country = $_GET['country']; 

    $query = "select * from elements where elementId=any(select elementId from citycategoryelements where cityId=" 
      . "any(select cityId from city where name='$city' and country='$country') and categoryId=any(" 
      . "select categoryId from categories where name='$category'))"; 

    $result = mysqli_query($dbc, $query); 

    if (!$result) { 
     echo "Could not successfully run query from DB: " . mysql_error(); 
     exit; 
    } 

    // Iterate through the rows, adding XML nodes for each 
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { 
     // Add to XML document node 
     $node = $dom->createElement("element"); 
     $newnode = $parnode->appendChild($node); 
     $newnode->setAttribute("name", $row['name']); 
     $newnode->setAttribute("address", $row['address']); 
    } 
    echo $dom->saveXML(); 
    ?> 

은 다음과 같이 보입니다 : XML 예를

<?xml version="1.0"?> 
<elements> 
    <element name="first_name" address="first_address"/> 
    <element name="second_name" address="second_address"/> 
</elements> 

그럼 난 자바 스크립트와 XML 파일을 처리하려고 :

var xmlhttp; 
if (window.XMLHttpRequest) 
{// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp = new XMLHttpRequest(); 
} 
else 
{// code for IE6, IE5 
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
} 

xmlhttp.onreadystatechange = function() 
{ 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    { 
     var xmlDoc = xmlhttp.responseXML; 
     var name = xmlDoc.getElementsByTagName("element")[0].getAttribute("name"); 
     alert(name); 
    } 
} 
xmlhttp.open("GET", "getElements.php?category=" + encodeURIComponent(category) + 
       "&city=" + encodeURIComponent(address[0]) 
       + "&country=" + encodeURIComponent(address[1]), true); 
       //xmlhttp.open("get", "file.xml", true); 
       xmlhttp.send(); 
} 

을 코드를 실행하려고하면 경고가 나타나지 않습니다. 또한 xmlDoc에 경고하려고하면 null이 표시됩니다.

내가 작동 처음 xmlthttp.open 대신에 그것을 사용하는 경우 당신은 내가이 댓글 //xmlhttp.open("get", "file.xml", true)

있는 것을 볼 수있다 (당신이 짐작 수 있으므로 file.xml는 위의 예처럼 보이는 단지 일반 XML 파일입니다) . 문제가 무엇인지 모르겠다. PHP 스크립트가 유효한 XML 파일을 반환한다고 확신한다. 누군가가 나를 도울 수 있다면 그것은 좋을 것입니다, 미리 감사드립니다! 때문에,

TypeError: xmlDoc.getElementsByTagName(...)[0] is undefined

+0

을 재현 할 수 없습니다. 이것이 어떤 종류의 내부 또는 테스트 응용 프로그램이 아니면 않는 한. – Swippen

+1

콜백 함수의'xmlDoc = xmlhttp.responseXML; 라인 바로 뒤에'xmlDoc'의 내용을 로깅 할 수 있습니다. –

+0

'console.log (xmlhttp); 또한 XML 대신 JSON을 보내는 것이 더 쉬울 수도 있습니다 – Steve

답변

0

TypeError: xmlDoc.getElementsByTagName(...)[0] is undefined

xmlDoc 정의하는 것을 의미 : 편집

도 나는 방화범을 사용하고

내가 이런 식으로 뭔가를 얻을 경우 말을 잊었다 getElementsByTagName을 호출 할 수는 있지만 getElementsByTagName의 리턴은 inc가 아닙니다. 속성이 0인데, 이는 x[0]이 아니므로 getAttribute이 정의되지 않음입니다.

이것은 XML이 예상대로 구문 분석하지 않았 음을 나타냅니다. 출력을 표시하면 <element> 태그가 생성됩니다.

콘솔에서 xmlDoc을 검토하면 오류 메시지가 표시됩니다. 말했다


, 난 당신이 SQL 주입 정말 조심해야한다 그런데 당신의 오류

var xhr, b, uri; 
xhr = new XMLHttpRequest; 
xhr.onload = function() { 
    URL.revokeObjectURL(uri); 
    console.log(this.responseXML); 
}; 

b = new Blob(['<?xml version="1.0"?>\n\ 
<elements>\n\ 
    <element name="first_name" address="first_address"/>\n\ 
    <element name="second_name" address="second_address"/>\n\ 
</elements>'], {type: 'text/xml'}); 
uri = URL.createObjectURL(b); 

xhr.open('GET', uri); 
xhr.send(); 
+0

@fifth - 브라우저의 콘솔을 찾지 않았 으면 지시 사항을 확인하십시오. 'alert()'는 상당히 제한된 디버깅 도구입니다. –

+0

@Paul S - XML ​​파싱에 문제가있어서 도움을 주신 덕분에 처음에는 2 칸이 생겨 유효하지 않게되었습니다. 다시 한 번 감사의 말을 전합니다. 저에게 도움이되고 유용한 조언을 해 주신 모든 분들께 감사드립니다. – fifth