我正在 ajax 中完成本教程,但我不明白调用函数的其中一行。 (代码中的第6行)
// this is called from an onload event in the html body tag
function process() {
if (xmlHttp) {
try {
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.onreadystatechange = handleServerResponse; ***** THIS LINE HERE
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
};
}
handleServerResponse = function() {
theD = document.getElementById('theD');
if (xmlHttp.readyState == 1) {
theD.innerHTML += "Status 1: server connectino established <br />";
} else if (xmlHttp.readyState == 2) {
theD.innerHTML += "Status 2: request recieved <br />";
} else if (xmlHttp.readyState == 3) {
theD.innerHTML += "Status 3: server processing task <br />";
} else if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
try {
text = xmlHttp.responseText;
theD.innerHTML += 'status 4: request completed, response delievered.';
theD.innerHTML += '<br />' + text;
} catch(e) {
}
} else {
alert("request cannont be completed by server (status 4)");
};
};
}
为什么我不使用括号来调用它?例如:xmlHttp.onreadystatechange = handleServerResponse();
当我这样做时,它似乎只调用该函数一次,因为它只打印出状态 2。尽管没有括号,但当该函数被声明为变量时,它似乎每次状态更改时都会被调用。这是为什么?
另外,为什么 xmlHttp.onreadystatechange 属性会执行多次? body 标记只能加载一次,因此只能调用该函数一次。为什么会循环?
我肯定遗漏了一些东西,无论是与 ajax 相关的对象还是 JavaScript 函数调用。
除了下面的答案之外,这里还有对 process 函数中的“true”和“null”参数的很好的解释:http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
最佳答案
why wouldn't I call it with parenthesis? like: xmlHttp.onreadystatechange = handleServerResponse();
因为在这一行中您没有调用该函数。您只需订阅一个事件(回调),稍后当 AJAX 请求从服务器获得某些响应时,xmlHttp
实例将调用该事件。
当您调用 xmlHttp.send(null);
时,AJAX 请求将发送到服务器进行处理。该函数立即返回并执行下一行代码。稍后,当服务器完成执行请求时,它将向客户端返回一些状态代码以及响应正文。正是在此时,实际的 handleServerResponse
函数将被执行。
关于javascript 回调函数 onreadystatechange,在一个简单的 ajax 示例中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24599332/