就 XMLHttpRequest() 对象而言,没问题,问题出在 onreadystatechange 例如,如果我这样放置我的代码,它会完美运行。
function process(){
var xmlHttp = new XMLHttpRequest();
if(xmlHttp){
xmlHttp.onreadystatechange = function(){
theD = document.getElementById("theD");
if(xmlHttp.readyState == 1){
theD.innerHTML += "Status 1: Server connection established ! <br/>";
}
else if(xmlHttp.readyState == 2){
theD.innerHTML += "Status 2: Request recieved ! <br/>";
}
else if(xmlHttp.readyState == 3){
theD.innerHTML += "Status 3: Processing Request ! <br/>";
}
else if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var text = xmlHttp.responseText;
theD.innerHTML += "Status 4: Processing Request ! <br/>";
theD.innerHTML += text;
}
else{
alert("Something is wrong !");
}
}
};
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.send();
}
}
但如果我创建一个函数 handleServerResponse()
function handleServerResponse(){
theD = document.getElementById("theD");
if(xmlHttp.readyState == 1){
theD.innerHTML += "Status 1: Server connection established ! <br/>";
}
else if(xmlHttp.readyState == 2){
theD.innerHTML += "Status 2: Request recieved ! <br/>";
}
else if(xmlHttp.readyState == 3){
theD.innerHTML += "Status 3: Processing Request ! <br/>";
}
else if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var text = xmlHttp.responseText;
theD.innerHTML += "Status 4: Processing Request ! <br/>";
theD.innerHTML += text;
}
else{
alert("Something is wrong !");
}
}
}
并称它为
xmlHttp.onreadystatechange = handleServerResponse();
这是行不通的。如有错误请指出。
最佳答案
尝试使用
xmlHttp.onreadystatechange = handleServerResponse;
注意删除的括号。
关于javascript - onreadystatechange 函数在 AJAX 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463278/