gpt4 book ai didi

javascript - Resposexml 返回空值

转载 作者:行者123 更新时间:2023-11-28 04:59:13 27 4
gpt4 key购买 nike

我是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com