我正在用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函数调用所缺少的东西。
除了下面的答案外,这里还很好地说明了过程函数中的“ true”和“ null”参数:http : //www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
为什么不带括号来称呼它?像:xmlHttp.onreadystatechange = handleServerResponse();
因为在此行上您未调用功能。您只是在订阅一个事件(回调),该事件稍后将由xmlHttp
实例在AJAX请求从服务器获得响应时调用。
调用时xmlHttp.send(null);
,AJAX请求将发送到服务器进行处理。该函数立即返回,并执行下一行代码。稍后,服务器完成请求后,它将与响应主体一起向客户端返回一些状态代码。正是在那一刻,实际handleServerResponse
功能将被执行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句