AJAX流程

来源:互联网 发布:淘宝站外活动哪个好 编辑:程序博客网 时间:2024/06/05 02:41

创建一个XHR对象

var xmlhttp;if (window.XMLHttpRequest)  {// code for IE7+, Firefox, Chrome, Opera, Safari  xmlhttp=new XMLHttpRequest();  }else  {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }

或者写成try/catch形式

try{    var xmlhttp = new XMLHttpRequest();}catch(e){    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}

初始化请求 open()

xmlhttp.open("POST","ajax_test.php",true);xmlhttp.open("GET","ajax_test.php",true);

设置请求的HTTP头信息 setRequestHeader() 注:必须在open()后调用。

//用POST方法提交请求时,设置编码类型xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//提交COOKIExmlhttp.setRequestHeader("COOKIE","cookiename=cookievalue");//提交XMLxmlhttp.setRequestHeader("Content-Type","text/xml");

发送请求 send()

xmlhttp.send()

指定请求状态改变时的事件句柄处理 onreadystatechange

xmlhttp.onreadystatechange = function(){    //code}

获取当前请求状态 readyState对象

  0(未初始化)-对象已经创建,但未调用open方法初始化;

  1(初始化)-对象已经初始化,但未调用send方法;

  2(发送数据)-send方法已经被调用,但是HTTP状态和HTTP头未知;

  3(数据传送中)-已经开始接收数据,但由于响应数据和HTTP头信息不全,这时尝试获取数据会出现错误;

  4(完成)-数据接收完毕。

if(xmlhttp.readyState == 4){    //code}

返回当前请求的HTTP状态码 status属性

if(xmlhttp.status == 200){    //code}

从返回信息中获取指定的HTTP头

xmlhttp.getResponseHeader("property")

获取返回信息的所有HTTP头 getAllResponseHeaders()

xmlhttp.getAllResponseHeaders()

取得返回的数据

xmlhttp.responseText;//XMLxmlhttp.responseXML;

取消当前请求

xmlhttp.abort();

最终版本

//创建XHR对象try{    var xmlhttp = new XMLHttpRequest();}catch(e){    var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}//初始化请求xmlhttp.open("POST","ajax_test.php",true);//设置请求的HTTP头信息xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//指定请求状态改变时的事件句柄处理xmlhttp.onreadystatechange = function(){    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){        //获取返回信息的所有HTTP头        alert(xmlhttp.getAllResponseHeaders());        //取得返回的数据        alert(xmlhttp.responseText);        alert(xmlhttp.responseXML);    }}//发送请求xmlhttp.send();
0 0
原创粉丝点击