2015-11-06 119 views
0

因此,我有一个Materialise基于CSS的网站。 Materialise CSS是一个CSS库,可在此处获得,link将两个Feed合并为一个

现在,我设法显示我的博客饲料分为两列,第一行,然后是第二行。

------------------------ 
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> 

现在,我想添加在另一个feed中,以当前显示的方式显示。比方说,YouTube视频供稿。它需要按照正确的时间顺序显示在相同的两列中,两个Feed都是混合的。

我该怎么做?

回答

0

首先结合两个数据流,使用$.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) 
}); 
+0

看起来像这样会工作。但是,如果视频XML使用标签,我更改第三个代码片段的第一行以找到Entry标签而不是Item,对吧? – FoxInFlame

+0

准确地说,无论你需要做什么来获取物品清单。 –

+0

哦,不,但对于YouTube来说,它会变为,以获取视频的作者和URL,然后转换成以获取视频名称和说明。它只是'find('media:group')'? – FoxInFlame