2011-11-08 65 views
0

如何同步嵌套的ajax調用?

function SomeFunc() { 
    $.when($.ajax()).then(FunctionWhichDoesMoreAjax()); 
} 

現在我需要環繞這一另一個電話。

$.when(SomeFunc()).then(FunctionWhichDoesMoreAjax2());

我試圖修改SomeFunc()

function SomeFunc() { 
    return $.when($.ajax()).then(return FunctionWhichDoesMoreAjax()); 
} 

但是,這完全打破了功能。該IDE報告錯誤

預計表達

回報FunctionWhichDoesMoreAjax());

我應該如何對這些同步跟進?

+0

見梅德的答案;我假設是因爲'FunctionWhichDoesMoreAjax()'之前的'return',你最終試圖從其成功回調中返回一個值。對困惑感到抱歉。 –

回答

3

試試這個:

function SomeFunc() { 
    return $.when($.ajax()).then(FunctionWhichDoesMoreAjax); 
} 
+0

我讀到的問題是能夠鏈接兩個Ajax調用。 OP沒有說他想要第二個函數的返回值。如果是這樣的話,那麼我同意你的回答:這不能用異步調用完成。 –

+0

刪除了我原來的評論;如果'FunctionWhichDoesMoreAjax'也是'$ .when(...)。then(function(){...})';我不確定什麼是回報價值。 –

+0

啊,你是對的;沒有人說關於回報價值。 –

0

你真正需要的ID發送到服務器端控制器處理Ajax請求。 可用性的一個好方法,在你的心中,你可以在任何情況下使用兩個位。 首先位置將具有所述請求和所述第二數據例如JSON數據或任何其他的ID。 當服務器端完成其工作,它在一個陣列也是同樣的模式,ID,數據和你做響應發送回頁面。您可以在頁面中發送異步,而不用擔心混淆請求。

function request1(){ 
    data=getdata; 
    arrData={1,data}; 
    ajaxsent(controler,data,onresponse1); 

} 

function request2(){ 
    data=getdata 
    arrData={2,data}; 
    ajaxsent(controler,data,onresponse2); 
} 

function request3(){ 
    data=getdata; 
    arrData={3,data}; 

    ajaxsent(controler,data,onresponse3); 
} 

function request4(){ 
    data=getdata; 
    arrData={4,data}; 
    ajaxsent(controler,data,onresponse4); 
} 

function onresponse1(xml){ 
    synchronizer(xml); 
} 

function onresponse2(xml){ 
    synchronizer(xml); 
} 

function onresponse3(xml){ 
    synchronizer(xml); 
} 

function onresponse4(xml){ 
    synchronizer(xml); 
} 

function synchronizer(xml){ 
    switch(xml.id) 
    case 1: dostuff; 
    case 2: dostuff; 
    case 3: dostuff; 
    case 4: dostuff; 

}