我使用下面的代码来拥有多个ajax请求,如下所示:
1,启动,,请求,1,完成,请求,2,2,2,,,.
这是代码:
var startingpoint = fireRequest(1);
$.each(types,function(ix,type)
{
startingpoint = startingpoint.pipe( function()
{
alert(startingpoint.status); // undefined
return fireRequest(type);
});
});fireRequest只是一个正确的ajax函数的转换,它返回$.ajax(.)
当一个请求失败时,我希望链子停止。我开始实现它,作为测试,我想提醒ajax对象的状态,但是它显示“未定义”。我怎样才能得到身份?
发布于 2012-10-09 14:30:35
您要实现的行为已经是.pipe()方法的行为。它接受两个回调作为参数,并且只执行已完成的回调,并在前一个请求成功的情况下沿着链继续。这可以在下面的jsfiddle中得到说明:http://jsfiddle.net/dflor003/Vq2YF/ (注意:在具有内置JSON.stringify支持和console.log支持的浏览器中打开它)
如果您确实希望检查请求的状态,它将接受状态作为已完成回调的第二个参数。更多细节可以在jQuery的API文档站点上找到:http://api.jquery.com/deferred.pipe/
发布于 2012-10-08 03:32:41
JS示例1
此代码假定,如果任何一个请求失败(通过404或500响应,或超时),您希望中止其他请求,并且不需要评估数据响应来确定业务逻辑失败场景。$.when()
该方法将在所有Deferreds解决后立即解析其主延迟,或在其中一个Deferred被拒绝时立即拒绝主延迟。
$.when(fireRequest(1), fireRequest(2),fireRequest(3))
.then(myAllSuccessfulFunc, oneFailedFunc);
function myAllSuccesfulFunc(req1,req2,req3){
//everything returned a 200.
alert("these are not the droids you are looking for");
};
function oneFailedFunc(req1,req2,req3){
//* each req looks like [ "not success", statusText, jqXHR ] */
//feel free to check what failed, but I don't know what you need
req1[2].abort();
req2[2].abort();
req3[2].abort();
};js示例2
实际上,您需要在响应中解析一个成功的数据请求,看看是否应该因为后端的逻辑而导致其他请求失败。
var stop = 4;
//if you are sure fireRequest(x) returns a good promise object, do this:
callNext(fireRequest(1),1);
function callNext(promise, currentIndex){
promise.done(function(ajaxArgs){
var jqXHR = ajaxArgs[2];
//replace this with some logic check that makes sense to your app
if(/error/.test(jqXHR.responseText)){
//do something
}else if(currentIndex <stop){
callNext(fireRequest(currentIndex+1),currentIndex+1);
}).fail(function(ajaxArgs){
//server returned a 404, or a 500, or something not a success.
});
};https://stackoverflow.com/questions/12707874
复制相似问题