【问题标题】:XMLHttpRequest.responseXML returns NULL from Ajax to .php pageXMLHttpRequest.responseXML 从 Ajax 返回 NULL 到 .php 页面
【发布时间】:2013-12-17 10:43:33
【问题描述】:

我有一个搜索框,人们可以在其中填写 ID。如果他们按下它旁边的按钮,我会向 php 文件发出 ajax 请求,该文件采用 ID,在 DB 中查找相关信息并应作为 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]

所以我有点迷路了。它被 regonized 为 application/xml 文件,但 XMLHttpRequest 只设置 responseText 而不是 responseXML。

谁能解释一下我没有看到什么。预先感谢!

【问题讨论】:

    标签: javascript ajax xmlhttprequest content-type


    【解决方案1】:

    对不起各位。找了这个问题2小时,刚去洗手间换个方式测试了一下。

    问题出在我的 PHP 文件中:

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

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

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

    确实有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多