ajax的使用原理

XMLHttpRequest对象
ajax的核心对象是XMLHttpRequest,首先创建一个跨浏览器的xhr方法,

function createXHR(){
var xhr;
try{
xhr = new XMLHttpRequest();
}catch(MS){
try{
xhr = new ActiveXObject('Msxml2.XMLHTTP');
}catch(MS){
try{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}catch{
xhr = null;
}
}
}
return xhr;
}

步骤

ajax最基本的使用可分4步:1.创建xhr对象;2.通过xhr的onreadystatechange方法处理服务器返回的数据;3.open方法做发送前准备;4.send方法发送请求。

ajax示例(get)

var xhr = createXHR();//创建xhr对象,方法见上篇文章
xhr.onreadystatechange = function(){//返回数据处理方法
if (xhr.readyState == 4){
if (xhr.status == 200){//判断完成状态
alert(xhr.responseText);//成功返回的数据
} else{
alert('Request was unsuccessful:' + xhr.status);//未成功返回错误信息
}
}
}
xhr.open('get','mjjcss.php?name1=value1&name2=value2','true');//准备状态
xhr.setRequestHeader('myHeader','myValue');//自定义的头部信息,不需要可省去
xhr.send(null);

onreadystatechange回调和readyState状态
XMLHttpRequest的readyState属性(表示周期状态)共5个值:
0:创建xhr对象;
1:执行完open方法;
2:执行完send方法;
3:开始下载数据进行交互;
4:下载数据完毕;
每次 readyState值改变,都会触发onreadystatechange回调,在回调函数中处理服务器返回的数据,readyState == 4是经常用到的。返回的数据如果是字符串格式的就是xhr.responseText,如果是xml格式的就是xhr.responseXML。

status状态
status是http返回的状态,200表示OK,404表示not found,304表示没有改变可以读取缓存。

查询数据
如果有查询字符串,通过"?"跟在ulr后边,并以"&"链接,查询字符串name1=value1的名称和值都必须经过encodeURIComponent()进行编码。

注意事项
方法还有2个地方需要注意:发送头部信息(如需要)setRequestHeader必须放在open和send之间才能成功;成功后的处理事件onreadystatechang必须放在open方法前,才能跨浏览器实现。

post方法
ajax发送请求最常用的除了上面介绍的get方法,还有post方法。open中的get方法,只请求数据,并不向服务器发送数据,因此send发送为null;post方法则可以向服务器发送数据,代码如下,

xhr.open('get','mjjcss.php','true');//准备状态
xhr.send('name1=value1&name2=value2');//发送数据
原文地址:https://www.cnblogs.com/bianyuan/p/2356430.html