我正在发出一个简单的 AJAX 请求并使用以下代码在 JS 控制台中记录响应。它工作得非常好,但困扰我的一件事是它从服务器返回了 3 个响应(见附图)。
任何人都可以解释为什么会这样吗?
var xmlHttp = newXMLHttpObj();
function newXMLHttpObj(){
var xml;
if(window.XMLHttpRequest){
xml = new XMLHttpRequest();
} else{
xml = new ActiveXObject("Microsoft.XMLHTTP");
}
return xml;
}
function ajaxHandler(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
//handle response
var response = xmlHttp.responseXML.documentElement;
console.log(response);
var name = response.getElementsByTagName("name")[0].firstChild.data;
var age = response.getElementsByTagName("age")[0].firstChild.data;
ajaxContent.innerHTML = "Name: " + name + "<br />Age: " + age;
} else{
setTimeout(ajaxHandler, 1000);
}
}
function ajaxProcess(){
var ajaxContent = document.getElementById("ajaxContent");
ajaxContent.innerHTML = "loading";
//check server is ready to comunicate
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4){
xmlHttp.open("POST", "/js/test.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = ajaxHandler;
xmlHttp.send("name=the chuff&age=26");
} else{
setTimeout(ajaxProcess, 1000); //restart ajaxProcess until ready to comunicate
}
}