这个例子虽然简单,但是可以通过debug模式来仔细研究一下ajax在执行过程中的执行顺序,页面加载时会先去执行handleStateChange(),但是执行的时候不会进到方法内,当点击按钮执行到xmlHttp.onreadystatechange = handleStateChange;时,程序 不会去执行handleStateChange()这个方法,执行open后才会再次进入handleStateChange()这个方法,执行send后会再次进入handleStateChange()这个方法,这个时候xmlHttp.readyState会一直往后执行,一直到状态4为止,这时数据就返回了。每当 XMLHTTP 对象的状态发生改变时,handleStateChange() 函数就会执行。
<
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
>
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=iso-8859-1" >
< title >Simple XMLHttpRequest </title>
< script type ="text/javascript" >
var xmlHttp;
function createXMLHttpRequest(){
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startRequest(){
createXMLHttpRequest();//创建XMLHttpRequest
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "simpleResponse.txt", true);
xmlHttp.send(null);
}
function handleStateChange(){
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById("test").innerHTML = xmlHttp.responseText;//返回simpleRespose.txt中的内容
}
}
}
</script>
</head>
< body >
< form action ="#" >
< input type ="button" value ="Start Basic Asynchronous Request" onclick ="startRequest();" />
< div id ="test" >
</div>
</form>
</body>
</html>
< html >
< head >
< meta http-equiv ="Content-Type" content ="text/html; charset=iso-8859-1" >
< title >Simple XMLHttpRequest </title>
< script type ="text/javascript" >
var xmlHttp;
function createXMLHttpRequest(){
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startRequest(){
createXMLHttpRequest();//创建XMLHttpRequest
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "simpleResponse.txt", true);
xmlHttp.send(null);
}
function handleStateChange(){
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById("test").innerHTML = xmlHttp.responseText;//返回simpleRespose.txt中的内容
}
}
}
</script>
</head>
< body >
< form action ="#" >
< input type ="button" value ="Start Basic Asynchronous Request" onclick ="startRequest();" />
< div id ="test" >
</div>
</form>
</body>
</html>
本文转自sucre03 51CTO博客,原文链接:http://blog.51cto.com/sucre/354158,如需转载请自行联系原作者