您的位置:首页 > 其它

实现AJAX的基本步骤

2015-01-04 19:59 435 查看
要完整实现一个AJAX异步调用和局部刷新,通常需要以下几个步骤:

(1)创建XMLHttpRequest对象,也就是创建一个异步调用对象.

//IE6以上
var xhr= new XMLHttpRequest();

//IE6
var xhr=new ActiveXObject("Microsoft.XMLHTTP")

(2)创建一个新的HTTP请求,并指定该HTTP请求的方法、URL及验证信息.

xhr.open(方法,url,是否异步)

(3)设置响应HTTP请求状态变化的函数.

<script type="text/javascript"> function getDoc(){
var xmlhttp;
if(window.xmlhttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//for IE6
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("?myId").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("?GET", index.php,true);
xmlhttp.send(); } </script> </head> <body>
<button type="button" onclick="getDoc()">请求数据</button> </body>

(4)发送HTTP请求.
xmlhttp.send();

(5)获取异步调用返回的数据.

(6)使用JavaScript和DOM实现局部刷新.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: