我一个接一个地有两个AJAX请求 -
var firstResult;
var secondResult;
FirstAjaxrequest({
callback: function (options, success, response) {
if(success)
{
firstResult = true;
}
else
{
firstResult = false;
}
}
});
SecondAjaxrequest({
callback: function (options, success, response) {
if(success)
{
secondResult= true;
}
else
{
secondResult= false;
}
}
});
DisplayMessage(); // This function should display a message depending on
FirstResult and secondResult
答案 0 :(得分:12)
您可以为每个请求创建一个变量,表示请求成功。分别为每个请求更改此变量,当成功请求时,然后调用您的函数。
在你的函数中,只需检查两个变量,如果它们都是真的,则两个请求都成功,否则至少有一个不成功,if()
条件将为假。
var firstResult = false,
secondResult = false;
FirstAjaxrequest({
callback: function (options, success, response) {
if(success) {
firstResult = true;
DisplayMessage();
}
}
});
SecondAjaxrequest({
callback: function (options, success, response) {
if(success) {
secondResult= true;
DisplayMessage();
}
}
});
function DisplayMessage(){
if(firstResult && secondResult){
//Both requests successful
} else {
//Either still waiting for a request to complete
// or a request was not successful.
}
}
答案 1 :(得分:1)
在EXTJS中可能有更好的方法,但是一个普通的JS解决方案是
var firstResult;
var secondResult;
var reqCount = 2;
var returnedCount = 0;
function isDone () {
returnedCount++
if ( returnedCount === reqCount ) {
console.log(firstResult, secondResult);
}
}
FirstAjaxrequest({
callback: function (options, success, response) {
if(success)
{
firstResult = true;
}
else
{
firstResult = false;
}
isDone();
}
});
SecondAjaxrequest({
callback: function (options, success, response) {
if(success)
{
secondResult= true;
}
else
{
secondResult= false;
}
isDone();
}
});
答案 2 :(得分:1)
试一试
FirstAjaxrequest({
callback: function (options, success, response) {
if(success)
{
firstResult = true;
}
else
{
firstResult = false;
}
SecondAjaxrequest({
callback: function (options, success, response) {
if(success)
{
secondResult= true;
}
else
{
secondResult= false;
}
DisplayMessage(); // Now we have access to first and second result as the
//as the second request is within the scope of the first request
},
scope: this // We can pass the first request to the second request as the context
});
}
});
答案 3 :(得分:0)
每个请求完成后,您应该检查是否收到了另一个请求的结果。 有点像这样:
var result1 = null;
var result2 = null;
function DoAjax() {
$.get(url1, {}, function (data) {
result1 = data;
DoSth();
});
$.get(url2, {}, function (data) {
result2 = data;
DoSth();
});
}
function DoSth() {
if(result1 != null && result2 != null) {
//...
}
}
答案 4 :(得分:0)
警告:jQuery回答。我不确定extjs
是否对Deferreds和Promises有类似的支持。
这是了解jQuery Deferred的绝佳机会:
$.when(firstAjaxrequest(...), secondAjaxrequest(...))
.then(function (firstResult, secondResult) {
...
});
这假设您的firstAjaxrequest
和secondAjaxrequest
函数都返回Deferred
或Promise
个对象,例如$.ajax
返回的对象。