就XMLHttpRequest()對象而言,它很好,問題出在onreadystatechange例如,如果我把我的代碼這樣,它的作品完美。onreadystatechange函數在AJAX中不工作
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();
它不工作。請指出,如果我錯了。
爲什麼這麼多fuss..Use'$ .ajax'而不是.. –
它改變這一點 - xmlHttp.onreadystatechange = handleServerResponse; –