就 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();
它不起作用。如果我错了,请指出。