2010-01-22 85 views
0

我需要从2个XMLHttpRequests生成一个结果。 我该如何同时提出请求并等待它们完成?加入ajax结果?

我虽然过的类似...

resp1=""; 
req1.onreadystatechange=function(){if(this.readyState=4)resp1==this.responseText;} 
req2.onreadystatechangefunction(){if(this.readyState=4) finish(this.responseText);} 
function finish(resp2){ 
if (resp1=="") setTimeOut(finish(resp2),200); 
else { 
... both are done... 
} 

我没有测试过,但是我认为这是可行的。 有没有更好的方法?我的代码需要尽可能短而且快速。

回答

1

你不需要计时器。

您只需检查每个回调是否已完成另一个回调,如果是,请致电finish

例如:

var resp1 = null, resp2 = null; 

req1.onreadystatechange = function() { 
    if (this.readyState === 4) { 
     resp1 = this.responseText; 
     if (resp2 !== null) finish(); 
    } 
}; 
req2.onreadystatechange = function() { 
    if (this.readyState === 4) { 
     resp2 = this.responseText; 
     if (resp1 !== null) finish(); 
    } 
}; 
+0

谢谢,你可以确认有对多线程的灾难没有可能性(被称为完成两次)?我不确定js是否使用多线程。 – graw 2010-01-22 17:04:06

+0

Javascript不支持多线程,所以你不需要担心它。 – SLaks 2010-01-22 17:08:08