2016-03-07 70 views
1

我有一個ajax請求,我用它從API中提取數據,並從提取的數據中創建一個表。現在我需要做同樣的事情,但要從兩個不同的URL中提取數據併合併到同一個表(retTable)。在Ajax中合併來自不同URL的數據

這裏是我當前的代碼(一個Ajax請求):

$.ajax(
    { 
     url : '/url/status', 
     type: "GET", 
     success:function(data, textStatus, jqXHR) 
     { 
      theRows = extract_status_data(data) 
     }, 
     error: function(jqXHR, textStatus, errorThrown) 
     { 
      alert('error') 
     } 
    }); 
} 

function extract_status_data(jsonDataRaw){ 
    jsonResultSect = jsonDataRaw['result'] 
    retTable = "" 
    for(key in jsonResultSect){ 
     statusParam = jsonResultSect[key] 

     a = statusParam['a'] 
     b = statusParam['b'] 
     c = statusParam['c'] 
     d = statusParam['d'] 
     e = statusParam['e'] 

     retTable += "<tr><td>" + dropDownList(key) + "</td><td>" + key + "</td><td>" + a + "</td><td>" + b + "</td><td>" + c + "</td><td>" + d + "</td><td>" + e + "</td></tr>" 

} 
    return retTable 
} 

如何將正確的數據來自兩個不同的URL結合?請指教。

+0

這是排序的數據還是順序無關緊要?我想你可以像'$('#mytable')。append(extract_status_data(data));'爲每個ajax請求執行一些操作。 –

+0

@JosephMarikle訂單確實重要,並且有意義。參數名稱(a,b,c ..)只是一個例子。在我的代碼中,它們具有含義的名稱, – Omri

+0

'a','b','c'等將保持原始順序。 *行*順序會改變。這裏有一個例子:https://jsfiddle.net/kp5w9xLu/。如果你運行足夠多的時間,那麼'test-result-2'的行偶爾會成爲第一行。 –

回答

1

我現在不能制定出一個真正強大的解決方案,但這裏是我想出了:https://jsfiddle.net/heejse8h/

基本上主要是你把所有的URL在數組中,並保持一個標誌變量遞增爲每個網址你拉。這可能是這樣的:

urls = [ 
    '/url/status', 
    '/url/status2' 
]; 

var i = 0; 

然後,當你執行AJAX,你要存儲在一些陣列

var result = []; 

對於在的jsfiddle我的AJAX調用,我用這個基本結構

$.ajax({ 
    url : urls[i], 
    type: "GET", 
    success: function(data) { 
    // simplified example of storing the results 
    // the example code from the fiddle is more 
    // involved. 
    result[key].push(data); 

    if(urls[++i] !== undefined){ 
     // if there is another URL, use the same 
     // ajax object (using `this`), extend it, 
     // changing only the URL, and call it. 
     // the important part is that the `this` 
     // object has a reference to the currently 
     // executing `success` method. 
     $.ajax($.extend(this, {url: urls[i]})); 
    } else { 
     // otherwise, we're at the end of our URLs 
     // and we can focus on final formatting and 
     // display of the data. 
     for(key in result){ 
     $('#mytable').append("<tr><td>" + dropDownList(key) + "</td><td>" + key + "</td>" + result[key].join('') + "</tr>"); 
     } 
    } 
    } 
}); 

在我本來希望充實了這一點,並使用DOM API實際創建節點,而不是常量毗連結束,但是這種解決方案已經從原來的代碼出現了差異相當雙向噸。您可能需要考慮創建一個解析對象的函數,而不是依賴於連接。

相關問題