如何使用 JavaScript 解析 RSS 提要?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10943544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse an RSS feed using JavaScript?
提问by Thiru
I need to parse an RSS feed (XML version 2.0) and display the parsed details in an HTML page.
我需要解析 RSS 提要(XML 2.0 版)并在 HTML 页面中显示解析的详细信息。
回答by haylem
Parsing the Feed
解析提要
With jQuery's jFeed
使用jQuery的jFeed
(Don't really recommend that one, see the other options.)
(真的不推荐那个,请参阅其他选项。)
jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
With jQuery's Built-in XML Support
使用jQuery的内置 XML 支持
$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
With jQueryand the Google AJAX Feed API
使用jQuery和Google AJAX Feed API
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
But that means you're relient on them being online and reachable.
但这意味着您依赖于他们在线且可访问。
Building Content
建筑内容
Once you've successfully extracted the information you need from the feed, you could create DocumentFragment
s (with document.createDocumentFragment()
containing the elements (created with document.createElement()
) you'll want to inject to display your data.
一旦您成功地从提要中提取了您需要的信息,您就可以创建DocumentFragment
s(document.createDocumentFragment()
包含document.createElement()
您想要注入以显示您的数据的元素(使用创建)。
Injecting the content
注入内容
Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.
在页面上选择您想要的容器元素并将您的文档片段附加到它,然后简单地使用 innerHTML 完全替换其内容。
Something like:
就像是:
$('#rss-viewer').append(aDocumentFragmentEntry);
or:
或者:
$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;
Test Data
测试数据
Using this question's feed, which as of this writing gives:
使用这个问题的 feed,在撰写本文时给出:
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
<title type="text">How to parse a RSS feed using javascript? - Stack Overflow</title>
<link rel="self" href="https://stackoverflow.com/feeds/question/10943544" type="application/atom+xml" />
<link rel="hub" href="http://pubsubhubbub.appspot.com/" />
<link rel="alternate" href="https://stackoverflow.com/q/10943544" type="text/html" />
<subtitle>most recent 30 from stackoverflow.com</subtitle>
<updated>2012-06-08T06:36:47Z</updated>
<id>https://stackoverflow.com/feeds/question/10943544</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license>
<entry>
<id>https://stackoverflow.com/q/10943544</id>
<re:rank scheme="http://stackoverflow.com">2</re:rank>
<title type="text">How to parse a RSS feed using javascript?</title>
<category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="javascript"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="html5"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="jquery-mobile"/>
<author>
<name>Thiru</name>
<uri>https://stackoverflow.com/users/1126255</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript" />
<published>2012-06-08T05:34:16Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html">
<p>I need to parse the RSS-Feed(XML version2.0) using XML and I want to display the parsed detail in HTML page, I tried in many ways. But its not working. My system is running under proxy, since I am new to this field, I don't know whether it is possible or not. If any one knows please help me on this. Thanks in advance.</p>
</summary>
</entry>
<entry>
<id>https://stackoverflow.com/questions/10943544/-/10943610#10943610</id>
<re:rank scheme="http://stackoverflow.com">1</re:rank>
<title type="text">Answer by haylem for How to parse a RSS feed using javascript?</title>
<author>
<name>haylem</name>
<uri>https://stackoverflow.com/users/453590</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript/10943610#10943610" />
<published>2012-06-08T05:43:24Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html"><h1>Parsing the Feed</h1>
<h3>With jQuery's jFeed</h3>
<p>Try this, with the <a href="http://plugins.jquery.com/project/jFeed" rel="nofollow">jFeed</a> <a href="http://www.jquery.com/" rel="nofollow">jQuery</a> plug-in</p>
<pre><code>jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
</code></pre>
<h3>With jQuery's Built-in XML Support</h3>
<pre><code>$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
</code></pre>
<h3>With jQuery and the Google AJAX APIs</h3>
<p>Otherwise, <a href="https://developers.google.com/feed/" rel="nofollow">Google's AJAX Feed API</a> allows you to get the feed as a JSON object:</p>
<pre><code>$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed &amp;&amp; data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
</code></pre>
<p>But that means you're relient on them being online and reachable.</p>
<hr>
<h1>Building Content</h1>
<p>Once you've successfully extracted the information you need from the feed, you need to create document fragments containing the elements you'll want to inject to display your data.</p>
<hr>
<h1>Injecting the content</h1>
<p>Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.</p>
</summary>
</entry></feed>
Executions
处决
Using jQuery's Built-in XML Support
使用 jQuery 的内置 XML 支持
Invoking:
调用:
$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
Prints out:
打印出来:
------------------------
title : How to parse a RSS feed using javascript?
author :
Thiru
https://stackoverflow.com/users/1126255
description:
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author :
haylem
https://stackoverflow.com/users/453590
description:
Using jQuery and the Google AJAX APIs
使用 jQuery 和 Google AJAX API
Invoking:
调用:
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('https://stackoverflow.com/feeds/question/10943544'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
Prints out:
打印出来:
------------------------
title : How to parse a RSS feed using javascript?
author : Thiru
description: undefined
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author : haylem
description: undefined
回答by Nahuel Barrios
Another deprecated(thanks to @daylight)option, and the easiest for me (this is what I'm using for SpokenToday.info):
另一个已弃用(感谢@daylight)选项,对我来说最简单(这是我用于SpokenToday.info 的):
The Google Feed APIwithout using JQuery and with only 2 steps:
不使用 JQuery的Google Feed API,只需 2 个步骤:
Import the library:
<script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript">google.load("feeds", "1");</script>
Find/Load feeds (documentation):
var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1'); feed.load(function (data) { // Parse data depending on the specified response format, default is JSON. console.dir(data); });
To parse data, check documentation about the response format.
导入库:
<script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript">google.load("feeds", "1");</script>
查找/加载提要(文档):
var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1'); feed.load(function (data) { // Parse data depending on the specified response format, default is JSON. console.dir(data); });
要解析数据,请查看有关响应格式的文档。
回答by Ukuser32
For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.
对于阅读本文的其他人(从 2019 年开始),不幸的是,大多数 JS RSS 阅读实现现在都不起作用。首先,Google API 已关闭,因此这不再是一种选择,并且由于 CORS 安全策略,您现在通常无法跨域请求 RSS 提要。
Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options(2015) I get the following:
使用https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options(2015)上的示例,我得到以下信息:
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.
这是正确的,是最终网站的安全预防措施,但现在确实意味着上述答案不太可能奏效。
My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.
我的解决方法可能是通过 PHP 解析 RSS 提要并允许 javascript 访问我的 PHP,而不是尝试访问最终目的地提要本身。
回答by Chetabahana
If you are looking for a simple and free alternative to Google Feed APIfor your rss widget then rss2json.comcould be a suitable solution for that.
如果您正在为您的 rss 小部件寻找一个简单且免费的Google Feed API替代方案,那么rss2json.com可能是一个合适的解决方案。
You may try to see how it works on a sample code from the api documentationbelow:
您可以尝试查看以下api 文档中的示例代码是如何工作的:
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
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);
}
}
});
}
google.setOnLoadCallback(initialize);
<html>
<head>
<script src="https://rss2json.com/gfapi.js"></script>
</head>
<body>
<p><b>Result from the API:</b></p>
<div id="feed"></div>
</body>
</html>
回答by Alireza Fattahi
If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/
如果你想使用一个普通的 javascript API,https://github.com/hongkiat/js-rss-reader/有一个很好的例子
The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/
https://www.hongkiat.com/blog/rss-reader-in-javascript/的完整说明
It uses fetch
method as a global method that asynchronously fetches a resource. Below is a snap of code:
它使用fetch
方法作为异步获取资源的全局方法。下面是一段代码:
fetch(websiteUrl).then((res) => {
res.text().then((htmlTxt) => {
var domParser = new DOMParser()
let doc = domParser.parseFromString(htmlTxt, 'text/html')
var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
})
}).catch(() => console.error('Error in fetching the website'))
回答by sdepold
You can use jquery-rssor Vanilla RSS, which comes with nice templating and is super easy to use:
您可以使用jquery-rss或Vanilla RSS,它们带有漂亮的模板并且非常易于使用:
// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
limit: 3,
layoutTemplate: '<ul class="inline">{entries}</ul>',
entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})
// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
document.querySelector("#your-div"),
"https://stackoverflow.com/feeds/question/10943544",
{
// options go here
}
);
rss.render().then(() => {
console.log('Everything is loaded and rendered');
});
See http://jsfiddle.net/sdepold/ozq2dn9e/1/for a working example.
有关工作示例,请参阅http://jsfiddle.net/sdepold/ozq2dn9e/1/。
回答by jimiayler
Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Pluginthat does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.
现在试图为此找到一个好的解决方案,我偶然发现了FeedEk jQuery RSS/ATOM Feed 插件,它在通过 jQuery Feed API解析和显示 RSS 和 Atom 提要方面做得很好。对于基本的基于 XML 的 RSS 提要,我发现它的工作原理非常棒,不需要服务器端脚本或其他 CORS 解决方法,它甚至可以在本地运行。