我对javascript编程很新,我发送xmlhttprequest,其回复是xml格式。当我使用代理并拦截响应时,我可以按预期和xml格式看到回复。但是我想检索响应并在html中显示值或只是一些警报。但是我收到xmlresponse为null的错误。为什么xmlhttp.responseXML的值为null。下面是我的代码。请问有没有人知道出了什么问题。
var xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET','http://remoteserver.net/search/myvalues?format=xml','true');
xmlhttp.send();
alert(xmlhttp.responseText);
alert(xmlhttp.responseXML);
var xmlresponse=xmlhttp.responseXML;
var latitude;
var longitude;
try{
if(xmlhttp.status==200){
x=xmlresponse.getElementsByTagName("place");
latitude=x.getAttribute("lat");
longitude=x.getAttribute("lon");
coordonates="the latitude is "+latitude+" and the longitude is "+longitude;
//document.getElementById("output").innerHTML=coordonates;
alert(coordonates);
}
}
catch(err)
{
document.getElementById("output").innerHTML=err.message;
}
到目前为止,我所拥有的信息How to get the response of XMLHttpRequest?也是http://www.w3schools.com/ajax/ajax_xmlhttprequest_response.asp
答案 0 :(得分:1)
您传递给xmlhttp.open();
的第三个参数是true,这意味着异步(请注意,您不应该引用true - 您希望传递一个真值,而不是字符串“true”。
这意味着该函数将立即返回,而实际请求将在后台发生。因此,如果您立即检查结果,真实请求将不会响应,您将看到无效。
在致电send()
之前,您应该使用以下内容:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
监听AJAX请求何时完成,然后在发生时提醒您。
P.S。如果你是Javascript的新手,我会建议不要使用w3schools - 它的示例代码质量不是很高,并且使用jQuery - 网络上的大多数网站都使用它来使很多东西变得更容易。虽然在Stack Overflow上提到“使用jQuery”通常会导致一场火焰战。
jQuery解决方案看起来像:
$.get('http://remoteserver.net/search/myvalues?format=xml').then(function (data) {
alert(data);
}, function (errror) {
alert("An error occurred");
});