参考回答:
通过实例化一个XMLHttpRequest对象得到一个实例,调用实例的open方法为这次ajax请求设定相应的http方法,相应的地址和是否异步,以异步为例,调用send方法,这个方法可以设定需要发送的报文主体,然后通过监听readystatechange事件,通过这个实例 的readyState属性来判断这个ajax请求状态,其中分为0,1,2,3,4这四种状态(0未初始化,1载入/正在发送请求2载入完成/数据接收,3交互/解析数据,4接收数据完成),当状态为4的时候也就是接受数据完成的时候,这时候可以通过实例的status属性判断这个请求是否成功var xhr = new XMLHttpRequest();
xhr.open('get', 'aabb.php', true);
xhr.send(null);
xhr.onreadystatechange = function() {
if(xhr.readyState==4) {
if(xhr.status==200) {
console.log(xhr.responseText);
}
}
}
使ajax请求按照队列顺序执行,通过调用递归函数://按顺序执行多个ajax命令,因为数量不定,所以采用递归
function send(action, arg2) {
//将多个命令按顺序封装成数组对象,递归执行
//利用了deferred对象控制回调函数的特点
$.when(send_action(action[0], arg2))
.done(function () {
//前一个ajax回调函数完毕之后判断队列长度
if (action.length > 1) {
//队列长度大于1,则弹出第一个,继续递归执行该队列
action.shift();
send(action, arg2);
}
}).fail(function (){
//队列中元素请求失败后的逻辑
//重试发送
//send(action, arg2);
//忽略错误进行下个
//if (action.length > 1) {
//队列长度大于1,则弹出第一个,继续递归执行该队列
// action.shift();
// send(action, arg2);
//}
});
}
//处理每个命令的ajax请求以及回调函数
function send_action(command, arg2) {
var dtd = $.Deferred();//定义deferred对象
$.post(
"url",
{
command: command,
arg2: arg2
}
).done(function (json) {
json = $.parseJSON(json);
//每次请求回调函数的处理逻辑
//
//
//
//逻辑结束
dtd.resolve();
}).fail(function (){
//ajax请求失败的逻辑
dtd.reject();
});
return dtd.promise();//返回Deferred对象的promise,防止在外部修改状态
}