2011-02-10 84 views
7

我有一個函數可以從兩個位置獲取數據,並將返回的內容放置在顯示給用戶的模式對話框中。jQuery中的多個AJAX請求

這兩個請求都是異步的,因爲它們是跨域的。問題在於我不想顯示模式,直到兩個請求都完成加載。如何在加載模態之前檢查兩個請求是否已完成?

我已經嘗試將openModal函數放置在第二個請求的成功處理程序中,並且在第一個請求在第二個請求之前完成加載時有效,但有時並非如此。

這裏是我的代碼的副本:

function loadData(id) { 
$.ajax({ 
    type: 'GET', 
    url: 'https://someurl.com/v1.0/controller1/' + id, 
    dataType: 'jsonp', 
    success: function(data) { 
     // Do some stuff to the data 
    } 
}); 

$.ajax({ 
    type: 'GET', 
    url: 'https://someurl.com/v1.0/controller2/' + id, 
    dataType: 'jsonp', 
    success: function(data) { 
     // Do some stuff to the data 

     openModal(); 
    } 
}); 
} 

function openModal() { 
// Open the modal 
} 

回答

0

你可以把其中一個Ajax請求放在其他請求的成功回調中,但不會與同時請求他們一樣高效。然後,您只需將openModal調用放入內部ajax請求的成功回調中即可。不是最優的,如果這個解決方案能爲你工作,直到找到更好的選擇,它將是一個快速和容易的修復。

我會繼續思考這一個...

0
$.when(
    $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { 
     tags: "moon", 
     tagmode: "any", 
     format: "json" 
    }), 
    $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { 
     tags: "bird", 
     tagmode: "any", 
     format: "json" 
    })).then(function (res1, res2) { 

    });