2011-11-01 82 views
0

比方說,我有以下的javascript得到通知:

(function($) { 
    $.getJSON(url, function(data) { 
    $.each(data.rows, function(index, row) { 
     $.getJSON(url2, function(data2) { 
     //Do something with data2, like adding it to an element on the page. 
     //When all rows have been processed, by this function, I want to 
     //call a function. 
     } 
    } 
    } 
})(jQuery) 

我想通知所有內部$ .getJSON返回時。

在我的真實代碼中,我將使用一個回調函數,我希望在完成所有請求時調用它。

回答

3

你很可能jQuery.when()爲此,如:

(function($) { 
    $.getJSON(url, function(data) { 

    $.when.apply($, $(data.rows).map(function (idx, row) { 
     // return deferred object 
     return $.getJSON(url, function() { 
     // single callback 
     console.log('one done'); 
     }); 
    })) 
    .then(function() { 
     // success callback 
     console.log('success'); 
    }, function() { 
     // failure callback 
     console.log('failure'); 
    }); 
    }); 
})(jQuery) 

編輯:剛剛意識到when不會採取數組作爲參數,所以我改變了代碼使用.apply代替。

1

你知道你正在執行的第二個getJSON有多少,因爲它基於你從第一個獲得的數據的大小。因此,請記錄第二個getJSON已執行多少次,以及何時匹配原始數據的大小,您就完成了。

(function($) { 
    $.getJSON(url, function(data) { 
    var count = 0; 
    $.each(data.rows, function(index, row) { 
     $.getJSON(url2, function(data2) { 
     count++; 
     if(count === data.rows.length){ 
      console.log('all done!'); 
     } 
     } 
    } 
    } 
})(jQuery) 
0

我相信你正在尋找jQuery的whenthen函數。

用法示例:

var firstGet = $.getJSON(...), 
    secondGet = $.getJSON(...); 

$.when(firstGet(), secondGet()) 
.then(
    function (data1, data2) { alert('success!'); }, 
    function() { alert('fail'); } 
); 
+0

有了這種模式,我們必須知道我們需要多少「內部getJSON」(每個人需要一個變量),他不知道在「編碼時間」 – pomeh

+0

你是什麼意思?只需使用第一個getJSON返回的data.rows的長度即可 – jbabey

0

兩個答案都不錯。我只會注意到這種模式並不好,因爲我們假設你的第一個電話($.getJSON(url))返回了50個元素(不是那麼大),那麼你就可以非常高的同時製作50個AJAX請求!它可能會減慢瀏覽器併爲服務器創建開銷。 也許,第一個電話會返回你需要的所有數據?然後你的問題就解決了,你的服務器是安全的,你的用戶是最快樂的。