Jquery Queue请求集成一次首次请求成功,然后调用下一个请求
问题描述:
有什么方法可以集成Jquery Queue请求处理一旦第一个请求获得Success响应,然后调用下一个请求。Jquery Queue请求集成一次首次请求成功,然后调用下一个请求
仅供参考我用ajaxManager作为下面的代码,但它不等待先前的请求成功响应。
$(function() {
ajaxManager.run();
for (key in Reports) {
var Url = Reports[key];
if (Url != '') {
sendRequest(Url, key);
}
}
});
function sendRequest(Url, act_id) {
ajaxManager.addReq({
async: false,
cache: false,
url: Url,
type: "POST",
data: {},
dataType: "jsonp",
success: function(response) {
console.log(response);
}
});
}
有没有其他办法可以处理这个问题。
谢谢。
答
这里是你如何能做到这一个简单的例子(我保存在一个阵列上的报告)利用jQuery.queue(),jQuery.dequeue(),
var reports = [11, 12, 14, 15];
function doTheReport() {
if (reports.length === 0) {
alert('All reports are done now.');
return;
}
var report_Id = reports.pop();
$.ajax({
url: "/DoTheReport",
complete: function() {
doTheReport();
}
});
};
答
尝试
$(function() {
// requests url and data objects
var Reports = [{
"url": "url1",
"data": JSON.stringify([1])
}, {
"url": "url2",
"data": JSON.stringify([2])
}, {
"url": "url3",
"data": JSON.stringify([3])
}];
// all responses
var responses = [];
// jQuery.deferred , resolved when all requests completed
var requests = new $.Deferred() || $(requests);
// do stuff when all requests completed
requests.done(function (data) {
console.log(data);
alert(data.length + " requests completed");
$.each(data, function (k, v) {
$("#results").append(v + "\n")
})
});
// `request` fn
var request = function (url, data) {
return $.post(url, {
json: data
}, "json")
};
// `response` fn
var response = function (data, textStatus, jqxhr) {
// if response `textStatus` === `success` , do stuff
if (textStatus === "success") {
console.log(data, textStatus);
responses.push([textStatus, data, $.now()]);
// if items in queue , dequeue next item
if ($.queue(requests, "ajax").length) {
$.dequeue(requests, "ajax")
} else {
// if items not in queue , resolve requests
requests.resolve(responses)
}
};
};
// `error` fn
// var error = function() {};
// create queue of `request` functions
$.each(Reports, function (k, v) {
$.queue(requests, "ajax", function() {
return request(v.url, v.data)
.then(response /* , error */)
})
});
// dequeue first item in queue
$.dequeue(requests, "ajax")
})