两个 Feed 合并为一个

Two Feeds combined into one

所以,我有一个基于 Materialise CSS 的网站。 Materialise CSS 是一个 CSS 库,可在此处获得,link

现在,我设法将我的博客提要显示为两列,第一行向下,然后是第二行,就像这样。

------------------------
Newest     | 4th Newest
2nd Newest | 5th Newest
3rd Newest | 6th Newest
------------------------

这是上面代码中使用的代码。

<div class="row">
  <div id="firstColumnBlog" class="col s6"></div>
  <div id="secondColumnBlog" class="col s6"></div>
</div>
<script>
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "http://www.foxinflame.tk/blog/feed/",
        dataType: "xml",
        success: function (xml) {
            $(xml).find("item").each(function (eachCounter) {
                var title = $(this).find("title").text();
                var description = $(this).find("description").text();
                var comments = +($(this).find("slash:comments").text());
                var pubDate = $(this).find("pubDate").text();
                var link = $(this).find("link").text();
                if(eachCounter < 3){
                  $("#firstColumnBlog").append("<div class='postCollection'><div class='z-depth-1 blogpost' style='min-height: 300px'><br><h5><a style='color:black' href='"+link+"'>"+title+"</a></h5><br><p>"+description+"<br><i>"+comments+" Comments. Published at "+pubDate+"</i></p></div></div>");
                } else if(eachCounter < 6) {
                  $("#secondColumnBlog").append("<div class='postCollection'><div class='z-depth-1 blogpost' style='min-height: 300px'><br><h5><a style='color:black' href='"+link+"'>"+title+"</a></h5><p>"+description+"<br><i>"+comments+" Comments. Published at "+pubDate+"</i></p></div></div>");
                }
            });
        }
    });
  })
</script>

现在,我想添加另一个供稿,与当前供稿一起显示。比方说,YouTube 视频提要。它需要以正确的时间顺序显示在相同的两列中,并且两种提要混合显示。

我该怎么做?

首先使用 $.when.

合并两个数据流

$.ajax return 的调用称为 Promises 或 Deferred 对象。您不是提供成功函数,而是从 $.ajax 调用链接一个 done 方法。

$.ajax({
  type: "GET",
  url: "http://www.foxinflame.tk/blog/feed/",
  dataType: "xml"
}).done(function(xml) {
  // do stuff with xml
});

可以组合两个函数

var blogFeed  = $.ajax({ /* some settings */ });
var videoFeed = $.ajax({ /* some other settings */ });

$.when(blogFeed, videoFeed)
  .done(function(blogXML, videoXML) {
    // this will be called when both AJAX requests are successful
  });

当你达到这一点时,你可以简单地组合两个提要并使用自定义排序功能对它们进行排序。

var combined = blogXML.find('item').concat(videoXML.find('item'));

var sorted = combined.sort(function(a, b) {
  // not all date formats can be compared like this
  // but I don't know what format your dates are in
  var dateA = Date.parse(a.find('pubDate'));
  var dateB = Date.parse(b.find('pubDate'));
  return dateB - dateA;
});

sorted.forEach(function(item, index) {
  // do something with each item
  // (this will probably involve inserting them into the DOM)
});