Ajax完整的生命周期
2009-06-26 14:12 Peter Yao 阅读(3468) 评论(2) 编辑 收藏 举报写点关于AJAX生命周期的东西献给大家!
希望大家多多提点建议......
<html>
<head>
<script type="text/javascript">
var req=null;
var console=null;
var READY_STATE_UNINITIALIZED=0;
var READY_STATE_LOADING=1;
var READY_STATE_LOADED=2;
var READY_STATE_INTERACTIVE=3;
var READY_STATE_COMPLETE=4;
function sendRequest(url,parms,HttpMethod)
{
if(!HttpMethod)
{
HttpMethod="GET";
}
req=initXMLHTTPRequest();
if(req)
{
req.onreadystatechange=onReadyState;
req.open(HttpMethod,url,true);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.send(params);
}
}
function initXMLHTTPRequest()
{
var xRequest=null;
--------------------------------------
--------------初始化请求对象
if(window.XMLHttpRequest)
{
xRequest=new XMLHttpRequest();
}else if(window.ActiveXObject)
{
xRequest=new ActiveObject("Microsoft.XMLHTTP");
}return xRequest;
}
--------------------------------
function onReadyState() //定义回调函数
{
var ready=req.readyState;
var data=null;
if(ready==READY_STATE_COMPLETE) //检查readystate
{
data=req.responseText; //读取响应数据
}else
{
data="loading...["+ready+"]";
}
toConsole(data);
}
function toConsole(data)
{
if(console!=null)
{
var newline=document.createElement("div");
console.appendChild(newline);
var txt=document.createTextNode(data);
newline.appendChild(txt);
}
}
window.onload=function()
{
console=document.getElementById("console");
sendRequest("data.txt");
}
</script>
</head>
<body>
<div id="console"></div>
</body>
</html>
用微软的IE浏览其输出:
loading...[1]
loading...[1]
loading...[3]
Here is some text from the server!
在Mozilla的FireFox1.0版的 输出:
loading...[1]
loading...[1]
loading...[2]
loading...[3]
here is some text from the server!
回调函数的调用顺序与在IE中的情况累世,只是多了一次在readystate为加载 完成状态时(值为2)的回调!