1. Ajax的核心技术是xmlHttpRequest。
通过xmlHttpRequest中的open/send方法可以在不刷新当前页面的情况下向处理页发送数据;
通过xmlHttpRequest中的responseText属性和responseXML属性,可以得到处理页的输出结果。
2. 使用Ajax的几步
(1)首先创建xmlHttpRequest对象。
var xmlhttp = false;
//如果ActiveXObject存在,说明是IE5.0以上的版本,否则使用XMLHttpRequest创建
if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
(2)使用对象的open()方法创建新请求。
xmlhttp.open(rmethod,rurl,isAsync);
rmethod 指明请求的方法,如get()或post()
rurl 指明请求的页面
isAsync 是否异步,默认为true,即异步
(3)如果isAsync为true,那么当请求状态改变时,将调用onreadystatechange属性,该属性指定一个回调函数。
xmlhttp.onreadystatechange = reabackfunc; 或者
xmlhttp.onreadystatechange = function(){...}
(4)在回调函数中,首先通过readyState属性和status属性判断http的请求状态和http状态码。
readyState常用4,表示数据接收完毕。
status常用200,表示请求成功
xmlhttp.onreadystatechange=function(){
if(readyState==4 && status==200)
}
(5)使用responseText属性和responseXML属性,可以得到处理页的输出结果。
responseText属性将相应页面的输出信息作为字符串返回。 str=xmlhttp.responseText;
(6)使用send()方法来接收回应。send()方法可以传递数据,单取决于open()方法中的rmethod参数。
若rmethod为get时,数据是附在URL中进行传递的。
若rmethod为post,数据只能使用send()方法传递。 xmlhttp.send([rdate]);