Javascript Resposexml返回空值

Javascript Resposexml返回空值,javascript,php,html,ajax,Javascript,Php,Html,Ajax,我不熟悉ajax。我想创建一个简单的网页,其中包含一个按钮,如果单击会动态返回图像。但是responseXML返回空值。下面是javascript代码的一部分: function process() { if(xmlhttp.readyState==4 || xmlhttp.readyState==0) { xmlhttp.open("GET","image.php",true); xmlhttp.onreadystatechange = hand

我不熟悉ajax。我想创建一个简单的网页,其中包含一个按钮,如果单击会动态返回图像。但是responseXML返回空值。下面是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>";

?>

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

responseXML为空的原因是PHP文件中存在错误。
我想当内容类型为xml时,我们不能发送HTML标记。相反,我们可以做的是回显图像的源代码,并修改JavaScript文件以获取该源代码并使用img标记显示。

您刚才复制了该代码吗,因为在我的程序中,readystate已经是4了,如您所见。我在另一篇帖子上看到了几乎相同的回复。你刚才复制了那个代码吗?因为在我的程序readystate中,正如你所看到的,readystate已经是4了。我在另一篇帖子上看到了几乎相同的回复。
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.)