var req; //定义变量,用来创建xmlhttprequest对象 function creatReq() // 创建xmlhttprequest,ajax开始 { var url="ajaxServer.aspx"; //要请求的服务端地址 if(window.XMLHttpRequest) //非IE浏览器,用xmlhttprequest对象创建 { req=new XMLHttpRequest(); } else if(window.ActiveXObject) //IE浏览器用activexobject对象创建 { req=new ActiveXObject("Microsoft.XMLHttp"); } if(req) //成功创建xmlhttprequest { req.open("GET",url,true); //与服务端建立连接(请求方式post或get,地址,true表示异步) req.onreadystatechange = callback; //指定回调函数 req.send(null); //发送请求 } } function callback() //回调函数,对服务端的响应处理,监视response状态 { if(req.readystate==4) //请求状态为4表示成功 { if(req.status==200) //http状态200表示OK { Dispaly(); //所有状态成功,执行此函数,显示数据 } else //http返回状态失败 { alert("服务端返回状态" + req.statusText); } } else //请求状态还没有成功,页面等待 { document .getElementById ("myTime").innerHTML ="数据加载中 "; } } function Dispaly() //接受服务端返回的数据,对其进行显示 { document .getElementById ("result").innerHTML =req.responseText; } </script> </head> <body> <div id="result"></div> <input id="Button1" type="button" value="Get Time" onclick ="creatReq();"/> </body> </html>
< html xmlns ="http://www.w3.org/1999/xhtml" > < head > < title > xmlhttprequest ajax demo </ title > < script type ="text/javascript" language ="javascript" >