在 ajax 中合并来自不同 URL 的数据
Combine data from different URLs in ajax
我有一个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 实际创建节点而不是常量串联,但这个解决方案已经与原始代码有很大不同。 您可能需要考虑创建一个函数来分析对象而不是依赖于串联。
相关文章:
- 如何有效地将游戏数据存储在URL查询字符串中
- 如何从外部url寻址数据
- 在按钮单击时将图像URL数据显示到弹出框中,而无需禁用背景
- 如何创建一个组件,我可以设置在 Angular 2 中的属性中获取 URL 数据
- ajax调用url数据中的正斜杠
- 将状态的 URL 数据获取到模板中
- 通过AJAX打开的PHP文件-发出Captcha警报并发送url数据
- 如何在 HTML 网页中解析 JSON URL 数据
- 主干提取url数据格式错误
- 使用JS按类或ID从URL数据中获取内容
- D3中的两个csv http URL数据相同的图表
- 使用JSON URL数据动态填充HTML表
- 使用PHP Curl、Jquery In Loop获取多个url数据
- 在拖放过程中从外部远程图像读取URL数据
- 如何将JSON URL数据解析为给定的AngularJS dxChart变量
- 如何使用JSON从Reddit API提取url数据
- 安全、准确地将用户提供的URL数据插入HTML5文档的正确方法是什么?
- AJAX url数据发送与友好的url's在Wordpress
- 从作为blob的图像中获取url数据
- 如何在html文本框中获取url数据