我有以下运行良好的脚本:
url = 'http://external_source/feed_1.xml';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
values = data.responseData.feed.entries;
if (values[0]) {
for (i = 0; i <= values.length - 1; i++) {
document.write(values[i].title);
document.write(values[i].publishedDate);
}
}
}
});
我现在有第二个 Feed,即 url = 'http://external_source/feed_2.xml';
,并且我需要合并两个 Feed。我知道我可以重复上述过程并让 feed_1 显示在 feed_2 之上,但我需要合并两个 feed 并按 publishedDate
对 feed 条目进行排序。
我该如何去做呢?两个提要的结构完全相同,只是 title
和 publishedDate
最佳答案
由于您使用的是 jQuery,因此您可以使用 jQuery.when
。该页面底部的示例向您展示了如何在多个异步方法完成后回调。
由于您将返回这两个数据,因此您可以连接数组并随后对它们进行排序:
$.when( $.ajax( "/page1.json" ), $.ajax( "/page2.json" ) ).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].responseData.feed.entries.concat(a2[0].responseData.feed.entries)
});
关于javascript - 合并然后排序 2 个 feed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920369/