两个Feed合并为一个

Two Feeds combined into one

本文关键字:一个 Feed 合并 两个      更新时间:2023-09-26

所以,我有一个基于Materialize CSS的网站。MaterializeCSS是一个CSS库,在这里可以找到,链接。

现在,我设法将我的博客提要显示为两列,第一行,然后第二行,如下所示。

------------------------
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的调用返回所谓的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)
});