我使用以下代码来发出多个 ajax 请求,如下所示:
请求1 开始 |请求1 次完成 |请求2开始 |请求2 完成 | ...
这是代码:
var startingpoint = fireRequest(1);
$.each(types,function(ix,type)
{
startingpoint = startingpoint.pipe( function()
{
alert(startingpoint.status); // undefined
return fireRequest(type);
});
});
fireRequest 只是正确 ajax 函数的一个 switchcase,它返回 $.ajax(...)
我希望当一个请求失败时链停止。我开始实现它,作为一个测试,我想提醒 ajax 对象的状态,但它显示“未定义”。我怎样才能获得状态?
最佳答案
您尝试实现的行为已经是 .pipe() 方法的行为。它需要两个回调作为参数,并且只会执行完成的回调,并且如果前一个请求成功则沿着链继续。这可以在下面的 jsfiddle 中进行说明: http://jsfiddle.net/dflor003/Vq2YF/ (注意:在具有内置 JSON.stringify 支持和 console.log 支持的浏览器中打开此文件)
如果您确实想检查请求的状态,它将把状态作为完成回调的第二个参数。更多详细信息可以在 jQuery 的 API 文档站点上找到:http://api.jquery.com/deferred.pipe/
关于jquery-ajax 多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12707874/