Resposexml返回null值

时间:2017-02-17 07:49:07

标签: javascript php html ajax

我是ajax的新手。我想创建一个简单的网页,其中包含一个按钮,如果点击动态返回图像。但是responseXML返回null值。以下是javascript代码的一部分:

function process()
{
    if(xmlhttp.readyState==4 || xmlhttp.readyState==0)
    {
        xmlhttp.open("GET","image.php",true);
        xmlhttp.onreadystatechange = handleserverresponse;
        xmlhttp.send();
    }else{
        setTimeout('process()',1000);
    }
}

function handleserverresponse()
{
    if(xmlhttp.readyState==4){
        if(xmlhttp.status==200){    
            xmlResponse = xmlhttp.responseXML;
            imag = xmlResponse.documentElement.firstChild.data;
            document.getElementById("divimg").innerHTML=imag;
        }
        else{
            alert("something went wrong");
        }
    }

这是php代码:

<?php
header('Content-Type:text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

echo "<res>";
echo "<img src="a.jpg"/>";
echo "</res>";

?>

2 个答案:

答案 0 :(得分:0)

Your HTTP request is asynchronous. xmlhttp.responseXML won't have some value until xmlhttp.readyState has the value of 4.

var url = "http://localhost/xml.php?type=xml";
var xmlhttp;
if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
    xmlhttp.open("GET", url, true);
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            alert(xmlhttp.responseXML);
        }
    };
    xmlhttp.send();
}
Additionaly, I don't think you need the setRequestHeader line. XML MIME type is required for response, not for request. Also, please respect good coding practices (don't forget var, DRY, etc.)

答案 1 :(得分:0)

responseXML之所以为null,是因为PHP文件中存在错误。 我想当内容类型为xml时,我们无法发送HTML标记。相反,我们可以做的是回显图像源并修改JavaScript文件以获取该源并使用img标记进行显示。