我有几个ajax请求返回不同的值(前面的伪代码)
var foo = "", bar = "", result = "";
$.ajax({
url : url1,
type : "GET",
data : data,
dataType: "json",
success : function(res) {
foo = "number of foo: " + res.foo;
}
});
$.ajax({
url : url2,
type : "GET",
data : data,
dataType: "json",
success : function(res) {
bar = "number of bar: " + res.bar;
}
});
等等。我想触发这些请求,然后合并结果并将它们呈现给用户
result = foo + "\n" + bar;
当然,由于请求是异步的,因此无法保证在我的代码准备好显示result
时foo
和bar
可用。我可以破解这样的东西
$.ajax({
url : url1,
type : "GET",
data : data,
dataType: "json",
success : function(res) {
result = "number of foo: " + res.foo + "\n";
$.ajax({
url : url2,
type : "GET",
data : data,
dataType: "json",
success : function(res) {
result += "number of bar: " + res.bar;
alert(result);
}
});
}
});
但是,这似乎不对。有关更好的解决方法的建议吗?
答案 0 :(得分:3)
使用jQuery-ajax的完整属性进行简单的更改:
var foo = "", bar = "", result = "", comp1=false, comp2=false;
$.ajax({
url : url1,
type : "GET",
data : data,
dataType: "json",
success : function(res) {
foo = "number of foo: " + res.foo;
},
complete: function(){
comp1=true;
comp1 && comp2 && triggerSomeEvent();
}
});
$.ajax({
url : url2,
type : "GET",
data : data,
dataType: "json",
success : function(res) {
bar = "number of bar: " + res.bar;
},
complete: function(){
comp2=true;
comp1 && comp2 && triggerSomeEvent();
}
});
function triggerSomeEvent(){//Handles completed `result`
result = foo + "\n" + bar;
//End then...
}
答案 1 :(得分:3)
您可以利用Ajax方法返回的jqXHR对象为deferred object这一事实。与$.when
[docs]一起,您可以:
$.when($.get(url1, data), $.get(url2, data)).done(function(a1, a2) {
var result1 = $.parseJSON(a1[2].responseText),
result2 = $.parseJSON(a2[2].responseText),
result = "number of foo: " + result1.foo + " number of bar: " + result2.bar;
// do other stuff
});