在 ajax 中合并来自不同 URL 的数据

Combine data from different URLs in ajax

本文关键字:URL 数据 ajax 合并      更新时间:2023-09-26

我有一个ajax请求,我用它来从API中提取数据,并从提取的数据创建一个表。现在我需要做同样的事情,但是从两个不同的URL中提取数据并合并到同一个表(retTable)。

这是我当前的代码(一个 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 的数据?请指教。

我现在无法敲定一个真正强大的解决方案,但这是我提出的:https://jsfiddle.net/heejse8h/

基本上,原则是将所有 URL 放在一个数组中,并为您从中提取的每个 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 实际创建节点而不是常量串联,但这个解决方案已经与原始代码有很大不同。 您可能需要考虑创建一个函数来分析对象而不是依赖于串联。