我想使用jQuery解析RSS feed。可以使用现成的基本jQuery库完成此操作,还是需要使用插件?
我想使用jQuery解析RSS feed。可以使用现成的基本jQuery库完成此操作,还是需要使用插件?
Answers:
警告
Google Feed API已正式弃用,无法再使用!
不需要整个插件。这会将您的RSS作为JSON对象返回给回调函数:
function parseRSS(url, callback) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
}
使用jFeed -jQuery RSS / Atom插件。根据文档,它很简单:
jQuery.getFeed({
url: 'rss.xml',
success: function(feed) {
alert(feed.title);
}
});
对于我们后面讨论的那些人,从1.5开始,jQuery具有内置的xml解析功能,这使得在没有插件或第3方服务的情况下轻松进行此操作非常容易。它具有parseXml函数,并且在使用$ .get函数时还将自动解析xml。例如:
$.get(rssurl, function(data) {
var $xml = $(data);
$xml.find("item").each(function() {
var $this = $(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text(),
description: $this.find("description").text(),
pubDate: $this.find("pubDate").text(),
author: $this.find("author").text()
}
//Do something with item here...
});
});
$this.find("link").text()
总是返回空字符串“”?
jFeed在IE中不起作用。
使用zRSSFeed。它在5分钟内工作了吗
更新(2019年10月15日)
我将核心逻辑从jquery-rss提取到一个名为Vanilla RSS的新库中,该库正在使用fetch API,并且可以在没有任何其他依赖项的情况下工作:
const RSS = require('vanilla-rss');
const rss = new RSS(
document.querySelector("#your-div"),
"http://www.recruiter.com/feed/career.xml",
{
// options go here
}
);
rss.render().then(() => {
console.log('Everything is loaded and rendered');
});
原版的
帖子:
您还可以使用jquery-rss,它具有不错的模板功能,并且超级易于使用:
$("#your-div").rss("http://www.recruiter.com/feed/career.xml", {
limit: 3,
layoutTemplate: '<ul class="inline">{entries}</ul>',
entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})
收益率(截至2013年9月18日):
<div id="your-div">
<ul class="inline">
<entries></entries>
</ul>
<ul class="inline">
<li><a href="http://www.recruiter.com/i/when-to-go-over-a-recruiter%e2%80%99s-head/">[@Tue, 10 Sep 2013 22:23:51 -0700] When to Go Over a Recruiter's Head</a><br>Job seekers tend to have a certain "fear" of recruiters and hiring managers, and I mean fear in the reverence and respect ...</li>
<li><a href="http://www.recruiter.com/i/the-perfect-job/">[@Tue, 10 Sep 2013 14:52:40 -0700] The Perfect Job</a><br>Having long ago dealt with the "perfect resume" namely God's, in a previous article of mine, it makes sense to consider the ...</li>
<li><a href="http://www.recruiter.com/i/unemployment-benefits-applications-remain-near-5-year-low-decline-again/">[@Mon, 09 Sep 2013 12:49:17 -0700] Unemployment Benefits Applications Remain Near 5-Year Low, Decline Again</a><br>As reported by the U.S. Department of Labor, the number of workers seeking unemployment benefits continued to sit near ...</li>
</ul>
</div>
有关工作示例,请参见http://jsfiddle.net/sdepold/ozq2dn9e/1/。
moment.js
function getFeed(sender, uri) {
jQuery.getFeed({
url: 'proxy.php?url=' + uri,
success: function(feed) {
jQuery(sender).append('<h2>'
+ '<a href="'
+ feed.link
+ '">'
+ feed.title
+ '</a>'
+ '</h2>');
var html = '';
for(var i = 0; i < feed.items.length && i < 5; i++) {
var item = feed.items[i];
html += '<h3>'
+ '<a href="'
+ item.link
+ '">'
+ item.title
+ '</a>'
+ '</h3>';
html += '<div class="updated">'
+ item.updated
+ '</div>';
html += '<div>'
+ item.description
+ '</div>';
}
jQuery(sender).append(html);
}
});
}
<div id="getanewbrowser">
<script type="text/javascript">
getFeed($("#getanewbrowser"), 'http://feeds.feedburner.com/getanewbrowser')
</script>
</div>
除非您的RSS数据是私有的,否则请使用Google AJAX Feed API。当然,它很快。
更新 [ 4/25/2016 ]现在更好地编写并完全受支持的版本,具有托管在 GitHub.jQRSS上的更多选项和功能
我看到所选答案由弥敦道Strutz,然而,jQuery插件页面链接仍下跌和该网站的主页上似乎没有负载。我尝试了其他一些解决方案,发现其中大多数解决方案不仅过时,而且简单!因此,我把帽子扔了出去,制作了自己的插件,并且这里有死链接,这似乎是提交答案的好地方。如果您在2012年(2013年b左右)寻找此答案,您可能会像我一样注意到这里的无效链接和旧建议。以下是我的现代插件示例以及该插件代码的链接!只需将代码复制到JS文件中,并像其他任何插件一样将其链接到标题中即可。使用是EXTREMELY EZ!
插件代码
2/9/2015-console
在向其发送命令之前进行了长时间的更新检查!应该可以解决较旧的IE问题。
(function($) {
if (!$.jQRSS) {
$.extend({
jQRSS: function(rss, options, func) {
if (arguments.length <= 0) return false;
var str, obj, fun;
for (i=0;i<arguments.length;i++) {
switch(typeof arguments[i]) {
case "string":
str = arguments[i];
break;
case "object":
obj = arguments[i];
break;
case "function":
fun = arguments[i];
break;
}
}
if (str == null || str == "") {
if (!obj['rss']) return false;
if (obj.rss == null || obj.rss == "") return false;
}
var o = $.extend(true, {}, $.jQRSS.defaults);
if (typeof obj == "object") {
if ($.jQRSS.methods.getObjLength(obj) > 0) {
o = $.extend(true, o, obj);
}
}
if (str != "" && !o.rss) o.rss = str;
o.rss = escape(o.rss);
var gURL = $.jQRSS.props.gURL
+ $.jQRSS.props.type
+ "?v=" + $.jQRSS.props.ver
+ "&q=" + o.rss
+ "&callback=" + $.jQRSS.props.callback;
var ajaxData = {
num: o.count,
output: o.output,
};
if (o.historical) ajaxData.scoring = $.jQRSS.props.scoring;
if (o.userip != null) ajaxData.scoring = o.userip;
$.ajax({
url: gURL,
beforeSend: function (jqXHR, settings) { if (window['console']) { console.log(new Array(30).join('-'), "REQUESTING RSS XML", new Array(30).join('-')); console.log({ ajaxData: ajaxData, ajaxRequest: settings.url, jqXHR: jqXHR, settings: settings, options: o }); console.log(new Array(80).join('-')); } },
dataType: o.output != "xml" ? "json" : "xml",
data: ajaxData,
type: "GET",
xhrFields: { withCredentials: true },
error: function (jqXHR, textStatus, errorThrown) { return new Array("ERROR", { jqXHR: jqXHR, textStatus: textStatus, errorThrown: errorThrown } ); },
success: function (data, textStatus, jqXHR) {
var f = data['responseData'] ? data.responseData['feed'] ? data.responseData.feed : null : null,
e = data['responseData'] ? data.responseData['feed'] ? data.responseData.feed['entries'] ? data.responseData.feed.entries : null : null : null
if (window['console']) {
console.log(new Array(30).join('-'), "SUCCESS", new Array(30).join('-'));
console.log({ data: data, textStatus: textStatus, jqXHR: jqXHR, feed: f, entries: e });
console.log(new Array(70).join('-'));
}
if (fun) {
return fun.call(this, data['responseData'] ? data.responseData['feed'] ? data.responseData.feed : data.responseData : null);
}
else {
return { data: data, textStatus: textStatus, jqXHR: jqXHR, feed: f, entries: e };
}
}
});
}
});
$.jQRSS.props = {
callback: "?",
gURL: "http://ajax.googleapis.com/ajax/services/feed/",
scoring: "h",
type: "load",
ver: "1.0"
};
$.jQRSS.methods = {
getObjLength: function(obj) {
if (typeof obj != "object") return -1;
var objLength = 0;
$.each(obj, function(k, v) { objLength++; })
return objLength;
}
};
$.jQRSS.defaults = {
count: "10", // max 100, -1 defaults 100
historical: false,
output: "json", // json, json_xml, xml
rss: null, // url OR search term like "Official Google Blog"
userip: null
};
}
})(jQuery);
用
// Param ORDER does not matter, however, you must have a link and a callback function
// link can be passed as "rss" in options
// $.jQRSS(linkORsearchString, callbackFunction, { options })
$.jQRSS('someUrl.xml', function(feed) { /* do work */ })
$.jQRSS(function(feed) { /* do work */ }, 'someUrl.xml', { count: 20 })
$.jQRSS('someUrl.xml', function(feed) { /* do work */ }, { count: 20 })
$.jQRSS({ count: 20, rss: 'someLink.xml' }, function(feed) { /* do work */ })
$ .jQRSS('在这里搜索单词而不是链接',function(feed){/ *起作用* /})
// TODO:需要修复
选件
{
count: // default is 10; max is 100. Setting to -1 defaults to 100
historical: // default is false; a value of true instructs the system to return any additional historical entries that it might have in its cache.
output: // default is "json"; "json_xml" retuns json object with xmlString / "xml" returns the XML as String
rss: // simply an alternate place to put news feed link or search terms
userip: // as this uses Google API, I'll simply insert there comment on this:
/* Reference: https://developers.google.com/feed/v1/jsondevguide
This argument supplies the IP address of the end-user on
whose behalf the request is being made. Google is less
likely to mistake requests for abuse when they include
userip. In choosing to utilize this parameter, please be
sure that you're in compliance with any local laws,
including any laws relating to disclosure of personal
information being sent.
*/
}
(function(url, callback) {
jQuery.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
})('http://news.hitb.org/rss.xml', function(feed){ // Change to desired URL
var entries = feed.entries, feedList = '';
for (var i = 0; i < entries.length; i++) {
feedList +='<li><a href="' + entries[i].link + '">' + entries[i].title + '</a></li>';
}
jQuery('.feed > ul').append(feedList);
});
<div class="feed">
<h4>Hacker News</h4>
<ul></ul>
</div>
我同意@Andrew的观点,使用Google是一种可靠且可重复使用的方法,这样做的好处是,您可以获取JSON而不是XML。将Google用作代理的另一个好处是,可能阻止您直接访问其数据的服务不太可能会阻止Google。这是使用滑雪报告和状况数据的示例。它具有现实世界中所有常见的应用程序:1)第三方RSS / XML 2)JSONP 3)当无法以所需的方式获取数据时清理字符串和字符串以进行数组4)加载时将元素添加到DOM。希望这对某些人有所帮助!
<!-- Load RSS Through Google as JSON using jQuery -->
<script type="text/javascript">
function displaySkiReport (feedResponse) {
// Get ski report content strings
var itemString = feedResponse.entries[0].content;
var publishedDate = feedResponse.entries[0].publishedDate;
// Clean up strings manually as needed
itemString = itemString.replace("Primary: N/A", "Early Season Conditions");
publishedDate = publishedDate.substring(0,17);
// Parse ski report data from string
var itemsArray = itemString.split("/");
//Build Unordered List
var html = '<h2>' + feedResponse.entries[0].title + '</h2>';
html += '<ul>';
html += '<li>Skiing Status: ' + itemsArray[0] + '</li>';
// Last 48 Hours
html += '<li>' + itemsArray[1] + '</li>';
// Snow condition
html += '<li>' + itemsArray[2] + '</li>';
// Base depth
html += '<li>' + itemsArray[3] + '</li>';
html += '<li>Ski Report Date: ' + publishedDate + '</li>';
html += '</ul>';
$('body').append(html);
}
function parseRSS(url, callback) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
}
$(document).ready(function() {
// Ski report
parseRSS("http://www.onthesnow.com/michigan/boyne-highlands/snow.rss", displaySkiReport);
});
</script>
jFeed已过时,仅适用于旧版jQuery。自更新以来已经两年了。
zRSSFeed的灵活性可能稍差一些,但易于使用,并且可以与当前版本的jQuery(当前为1.4)一起使用。http://www.zazar.net/developers/zrssfeed/
这是zRSSFeed文档中的一个简单示例:
<div id="test"><div>
<script type="text/javascript">
$(document).ready(function () {
$('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {
limit: 5
});
});
</script>
我正在将jQuery和yql用于提要。您可以使用yql检索twitter,rss,buzz。我从http://tutorialzine.com/2010/02/feed-widget-jquery-css-yql/阅读。对我来说非常有用。
我建议您使用FeedEk。正式弃用Google Feed API后,大多数插件将无法使用。但是FeedEk仍在工作。它非常易于使用,并且可以自定义很多选项。
$('#divRss').FeedEk({
FeedUrl:'http://jquery-plugins.net/rss'
});
有选项
$('#divRss').FeedEk({
FeedUrl:'http://jquery-plugins.net/rss',
MaxCount : 5,
ShowDesc : true,
ShowPubDate:true,
DescCharacterLimit:100,
TitleLinkTarget:'_blank',
DateFormat: 'MM/DD/YYYY',
DateFormatLang:'en'
});
<script type="text/javascript" src="./js/jquery/jquery.js"></script>
<script type="text/javascript" src="./js/jFeed/build/dist/jquery.jfeed.pack.js"></script>
<script type="text/javascript">
function loadFeed(){
$.getFeed({
url: 'url=http://sports.espn.go.com/espn/rss/news/',
success: function(feed) {
//Title
$('#result').append('<h2><a href="' + feed.link + '">' + feed.title + '</a>' + '</h2>');
//Unordered List
var html = '<ul>';
$(feed.items).each(function(){
var $item = $(this);
//trace( $item.attr("link") );
html += '<li>' +
'<h3><a href ="' + $item.attr("link") + '" target="_new">' +
$item.attr("title") + '</a></h3> ' +
'<p>' + $item.attr("description") + '</p>' +
// '<p>' + $item.attr("c:date") + '</p>' +
'</li>';
});
html += '</ul>';
$('#result').append(html);
}
});
}
</script>
使用由Google缓存的google ajax api和您想要的任何输出格式。
代码样本; http://code.google.com/apis/ajax/playground/#load_feed
<script src="http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0" type="text/javascript"></script>
<script type="text/javascript">
/*
* How to load a feed via the Feeds API.
*/
google.load("feeds", "1");
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
// Grab the container we will put the results into
var container = document.getElementById("content");
container.innerHTML = '';
// Loop through the feeds, putting the titles onto the page.
// Check out the result object for a list of properties returned in each entry.
// http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
}
function OnLoad() {
// Create a feed instance that will grab Digg's feed.
var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
google.setOnLoadCallback(OnLoad);
</script>
zRSSfeed建立在jQuery之上,简单的主题很棒。
试试看。
jQuery-rss项目非常轻巧,没有施加任何特定的样式。
语法可以很简单
$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")
jQuery Feeds是一个不错的选择,它具有内置的模板系统并使用Google Feed API,因此具有跨域支持。
jFeed很简单,并提供了一个示例供您测试。但是,如果要从另一台服务器解析提要,则需要在提要的服务器上允许跨源资源共享(CORS)。您还需要检查浏览器支持。
我上载了示例,但是当我通过http协议将示例中的URL更改为example.com/feed.rss时,仍然没有得到任何版本的IE支持。IE 8及更高版本应支持CORS,但jFeed示例未提供Feed。
最好的选择是使用Google的API:https:
//developers.google.com/feed/v1/devguide
参见:
https : //github.com/jfhovinne/jFeed
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
http://en.wikipedia.org/wiki/Same_origin_policy
http://caniuse.com/cors