2013-10-20 168 views
0

我試圖使用Jquery多個Ajax請求從PHP文件中獲取Json數據。這是我的代碼:

var req = $.when($.get('file.php?load=products'),$.get('file.php?load=config'),$.get('file.php?load=settings')); 

req.done(function(products,config,settings){ 
    console.log(products); 
    console.log(config); 
    console.log(settings); 
}); 

的問題是不是得到json的單獨請求的數據,該數據帶有像其他對象:Object { readyState=4, responseText="[{ "value": 5, "sku": ".../uploads/coffee.png" }]", status=200, more...}]當我試圖解析JSON數據從而導致錯誤發生。

當我看看我的PHP腳本返回的參數,一切看起來都很好,如果我不使用$.when方法,而是對每個ajax請求使用簡單的回調,它甚至可以正常工作。

我需要使用$.when方法,因爲我需要在這三個Ajax調用完成後執行一些操作。

希望你能幫助我,謝謝!

編輯: 好吧,我不知道爲什麼,但它工作,如果我使用:products[0]而不是products

回答

1

official documentation

實施例:執行一個函數經過兩次Ajax請求是成功的。 (請參閱jQuery.ajax()文檔以獲取有關ajax請求的成功和錯誤情況的完整說明)。

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2) { 
    // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. 
    // Each argument is an array with the following structure: [ data, statusText, jqXHR ] 
    var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" 
    if (/Whip It/.test(data)) { 
    alert("We got what we came for!"); 
    } 
}); 

所以你確實收到一個參數數組,每個ajax調用一個參數。每個參數是一組數字[data, textStatus, jqXHR]

通過閱讀產品[0],您正在訪問data

0

這可能看起來像一個大膽的,激進的舉動,但是 - 你是否考慮過只是採取你真正想使用的數據?那就是:products.responseText,config.responseTextsettings.responseText

+0

感謝您的評論,但'products.responseText'返回'undefined',如果我使用'products [0]'而不是 –