我的样本如下。我总是在“a”和“b”之前得到“c”。如何相应地获得“a”,“b”和“c”?我很感激任何建议。
b.extend({
get: function (id) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
}
});
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
}
});
}
console.log("c");
}
});
答案 0 :(得分:6)
尝试
将您的代码放入success:
b.extend({
get: function (id) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
if (a === 5) {
console.log("c");
}
}
});
}
}
});
}
});
答案 1 :(得分:2)
您还可以使用deferred:
b.extend({
get: function (id) {
var request = jQuery.ajax({
type: 'GET',
url: url,
data: pdata
}).then(function(result) {
console.log("a");
return result;
});
for (var a = 0; a < 5; a++) {
request = request.then(function(result) {
return jQuery.ajax({
type: 'GET',
url: url,
data: pdata
}).then(function(result) {
console.log("b");
return result;
});
});
}
request.then(function() {
console.log("c");
});
}
});
答案 2 :(得分:0)
在B的回调中调用C,在A的回调中调用B
答案 3 :(得分:0)
jQuery是异步的,因此一些Ajax请求可能先于其他请求完成。
b.extend({
get: function (id) {
var async = $.ajaxSetup()['async']; // store the current value of async to a variable
$.ajaxSetup({'async':false}); // Set async to false
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("a");
}
});
for (var a = 0; a < 5; a++) {
jQuery.ajax({
type: 'GET',
url: url,
data: pdata,
success: function (result) {
console.log("b");
}
});
}
console.log("c");
$.ajaxSetup({'async': async }); // Set async to back to original value
}
});
唯一的缺点是,在请求完成之前,您的页面将“挂起”