javascript - Resposexml 返回空值

标签 javascript php html ajax

我是 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>";

?>

最佳答案

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.)

关于javascript - Resposexml 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42292275/

相关文章:

html - 在 nowraps 之间换行

javascript - 在产品页面上输入文本字段而不是组合的下拉列表

javascript - 如何在javascript中突出显示重叠的字符串?

javascript - 输入值返回 NaN

php - 如何在PHP中的表格行中添加注释

php url 检查可用

php - 获取 e_date 中 90 天记录之前的用户数

javascript - 缩短我的 JS 和 HTML 代码

Javascript 幻灯片放映按钮不起作用

css - 在 Twitter Bootstrap 中将 .span9 内容居中?