step1. 创建XMLHttpRequest对象,也就是创建一个异步调用对象;
step2. 创建一个新的HTTP请求,并指定改HTTP请求的方法、URL以及验证信息;
step3. 设置响应HTTP状态变化的函数;
step4. 发送HTTP请求;
step5. 获取异步调用返回的数据;
step6. 使用javascript和DOM实现局部刷新;
重要代码实现:
<script>var xmlhttp;function createXMLHttpRequest(){xmlhttp=null;if (window.XMLHttpRequest){xmlhttp=new xmlHttpRequest(); //Netscape浏览器中的创建方式}else if(window.ActiveXObject){xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器的创建方式}//异步调用服务器段数据if(xmlhttp!=null){xmlhttp.open("GET/POST",url,true); //创建HTTP请求xmlhttp.onreadystatechange=httpStateChange;//设置HTTP请求状态变化的函数xmlhttp.send(null); //发送请求}else{alert("不支持XHR")}}//响应HTTP请求状态变化的函数function httpStateChange(){//判断异步调用是否完成if(xmlhttp.readyState==4){//readyState==4表示后台处理完成了if(xmlhttp.status==200||(xmlhttp.status==0){//状态码为0是本地响应成果,200表示处理的结果是ok的//判断异步调用是否成功,如果成功开始局部更新数据//code...}else{alert("出错状态码:"+xmlhttp.status+"出错信息:"+xmlhttp.statusText);}}}</script>• 1• 2• 3• 4• 5• 6• 7• 8• 9• 10• 11• 12• 13• 14• 15• 16• 17• 18• 19• 20• 21• 22• 23• 24• 25• 26• 27• 28• 29• 30• 31• 32• 33• 34
ajax例子:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>AJAX实例</title><script language="javascript" type="text/javascript">var xmlHttpRequest; //定义一个变量用于存放XMLHttpRequest对象//定义一个用于创建XMLHttpRequest对象的函数function createXMLHttpRequest(){if(window.ActiveXObject){//IE浏览器的创建方式xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");}else if(window.XMLHttpRequest){ //Netscape浏览器中的创建方式xmlHttpRequest = new XMLHttpRequest();}}//响应HTTP请求状态变化的函数function httpStateChange(){//判断异步调用是否完成if(xmlHttpRequest.readyState == 4){//判断异步调用是否成功,如果成功开始局部更新数据if(xmlHttpRequest.status == 200||xmlHttpRequest.status == 0){//查找节点var node = document.getElementById("myDIv");//更新数据node.firstChild.nodeValue = xmlHttpRequest .responseText;} else{//如果异步调用未成功,弹出警告框,并显示出错信息alert("异步调用出错/n返回的HTTP状态码为:"+xmlHttpRequest.status + "/n返回的HTTP状态信息为:" + xmlHttpRequest.statusText);}}}//异步调用服务器段数据function getData(name,value){//创建XMLHttpRequest对象createXMLHttpRequest();if(xmlHttpRequest!=null){//创建HTTP请求xmlHttpRequest.open("get","ajax.text",true)//设置HTTP请求状态变化的函数xmlHttpRequest.onreadystatechange = httpStateChange;//发送请求xmlHttpRequest.send(null);}}</script></head><body><div id="myDiv">原数据</div><input type = "button" value = "更新数据" onclick = "getData()"></body></html>
