主页.html
front page test
测试.php
<SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
<button type="button" onclick="callAJAX('home.html','displaydiv')">Click Me!</button>
<div id="displaydiv"></div>
ajax.js
function callAJAX(url, pageElement, callMessage) {
document.getElementById(pageElement).innerHTML = callMessage;
try {
req = new XMLHttpRequest(); /* e.g. Firefox */
} catch(e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
/* some versions IE */
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
/* some versions IE */
} catch (E) {
req = false;
}
}
}
req.onreadystatechange = function() {responseAJAX(pageElement);};
req.open("GET",url,true);
req.send(null);
}
function responseAJAX(pageElement) {
console.log(req.readyState);
var output = '';
if (req.readyState == 4) {
if (req.status == 200) {
output = req.responseText;
document.getElementById(pageElement).innerHTML = output;
}
}
}
上面的代码主要来自这里:
问题:
根据this site,onreadystatechange存储一个函数(或函数的名称),每次readyState属性更改时都会自动调用,那么属性何时
readyState
更改?之后req.send(null);
?对于这一行:
console.log(req.readyState);
在chrome控制台中,它显示:1 2 3 4
,它不输出0,是因为0: request not initialized
?