XMLHttpRequest.responseXML从Ajax返回NULL到.php页面

时间:2013-12-01 19:25:57

标签: javascript ajax xmlhttprequest content-type

我有一个搜索框,人们可以在其中填写ID。如果他们按下它旁边的按钮,我有一个ajax请求到一个获取ID的php文件,在数据库中查找相关信息并应该作为XML页面返回。

loadContact.php

<?php
header("Content-type: application/xml"); 
include('../classes/php.php');
$contactID = $_POST["contactID"];
$mItemArray = getItemFromID($contactID);
echo "
<?xml version=\"1.0\" encoding=\"utf-8\" ?> 
<app naam=\"send-to-work\" id=\"50029154\">
<contact id=\"" . $contactID . "\">
    <team>" . $mItemArray['Team'] . "</team> 
    <role>" . $mItemArray['Role'] . "</role> 
    <name>" . $mItemArray['Name'] . "</name> 
    <firstname>" . $mItemArray['Fname'] . "</firstname> 
    <phone>" . $mItemArray['Phone'] . "</phone> 
    <email>" . $mItemArray['Email'] . "</email> 
</contact>
</app>
";
?>

js.js

function loadContact()
{
var xmlhttp;
var x;
var contactID = $("input#id").val();
if (contactID != "" && contactID == parseInt(contactID)){
    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==404)
        {
            alert("PAGE NOT FOUND");
        }
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
           try{
            x=xmlhttp.responseXML   ;
           }
           catch(error){
               alert("error " + error);
           }
            alert(x);
            alert(xmlhttp.getResponseHeader("Content-Type"));
        }
    }
    xmlhttp.open("POST","ajax/loadContact.php",true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    xmlhttp.send("contactID="+contactID);
}
}

我目前得到的是:

x = null
xmlhttp.getResponseHeader("Content-Type") = application/xml.
xmlhttp.responseText //returns the correct page with the correct data. 
xmlhttp.open("POST","test.xml",true) //DOES set the responseXML as x = [object Document]

所以我有点失落。它被重新命名为application / xml文件,但XMLHttpRequest只设置responseText而不是responseXML。

任何人都可以向我解释我没有看到的内容。先谢谢!

1 个答案:

答案 0 :(得分:2)

我很抱歉。我正在寻找这个问题2个小时,只是去洗手间并以其他方式进行测试。

问题出在我的PHP文件中:

echo "
<?xml version=\"1.0\" encoding=\"utf-8\" ?> 

不起作用,因为XML声明(?)应该在第一行。

echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?> 

确实有效。