121

RSSフィード(XMLバージョン2.0)を解析し、解析された詳細をHTMLページに表示する必要があります。

4

9 に答える 9

220

フィードの解析

jQueryjFeedを使用

(実際にはお勧めしません。他のオプションを参照してください。)

jQuery.getFeed({
   url     : FEED_URL,
   success : function (feed) {
      console.log(feed.title);
      // do more stuff here
   }
});

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());
    });
});

jQueryGoogleAJAXFeedAPIを使用

$.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);
      });
    }
  }
});

しかし、それはあなたがそれらがオンラインで到達可能であることを信頼していることを意味します。


コンテンツの構築

フィードから必要な情報を正常に抽出したら、データを表示するために挿入する要素(で作成された要素DocumentFragmentを含む)を作成できます。document.createDocumentFragment()document.createElement()


コンテンツを挿入する

ページ上で必要なコンテナ要素を選択し、それにドキュメントフラグメントを追加し、innerHTMLを使用してそのコンテンツを完全に置き換えます。

何かのようなもの:

$('#rss-viewer').append(aDocumentFragmentEntry);

また:

$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;

テストデータ

この質問のフィードを使用すると、この記事の執筆時点で次のようになります。

<?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">
            &lt;p&gt;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&#39;t know whether it is possible or not. If any one knows please help me on this. Thanks in advance.&lt;/p&gt;

        </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">&lt;h1&gt;Parsing the Feed&lt;/h1&gt;

&lt;h3&gt;With jQuery&#39;s jFeed&lt;/h3&gt;

&lt;p&gt;Try this, with the &lt;a href=&quot;http://plugins.jquery.com/project/jFeed&quot; rel=&quot;nofollow&quot;&gt;jFeed&lt;/a&gt; &lt;a href=&quot;http://www.jquery.com/&quot; rel=&quot;nofollow&quot;&gt;jQuery&lt;/a&gt; plug-in&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery.getFeed({
   url     : FEED_URL,
   success : function (feed) {
      console.log(feed.title);
      // do more stuff here
   }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;With jQuery&#39;s Built-in XML Support&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$.get(FEED_URL, function (data) {
    $(data).find(&quot;entry&quot;).each(function () { // or &quot;item&quot; or whatever suits your feed
        var el = $(this);

        console.log(&quot;------------------------&quot;);
        console.log(&quot;title      : &quot; + el.find(&quot;title&quot;).text());
        console.log(&quot;author     : &quot; + el.find(&quot;author&quot;).text());
        console.log(&quot;description: &quot; + el.find(&quot;description&quot;).text());
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;With jQuery and the Google AJAX APIs&lt;/h3&gt;

&lt;p&gt;Otherwise, &lt;a href=&quot;https://developers.google.com/feed/&quot; rel=&quot;nofollow&quot;&gt;Google&#39;s AJAX Feed API&lt;/a&gt; allows you to get the feed as a JSON object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$.ajax({
  url      : document.location.protocol + &#39;//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;amp;num=10&amp;amp;callback=?&amp;amp;q=&#39; + encodeURIComponent(FEED_URL),
  dataType : &#39;json&#39;,
  success  : function (data) {
    if (data.responseData.feed &amp;amp;&amp;amp; data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        console.log(&quot;------------------------&quot;);
        console.log(&quot;title      : &quot; + e.title);
        console.log(&quot;author     : &quot; + e.author);
        console.log(&quot;description: &quot; + e.description);
      });
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But that means you&#39;re relient on them being online and reachable.&lt;/p&gt;

&lt;hr&gt;

&lt;h1&gt;Building Content&lt;/h1&gt;

&lt;p&gt;Once you&#39;ve successfully extracted the information you need from the feed, you need to create document fragments containing the elements you&#39;ll want to inject to display your data.&lt;/p&gt;

&lt;hr&gt;

&lt;h1&gt;Injecting the content&lt;/h1&gt;

&lt;p&gt;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.&lt;/p&gt;
</summary>
    </entry></feed>

処刑

jQueryの組み込みXMLサポートの使用

呼び出し:

$.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());
    });
});

プリントアウト:

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

jQueryとGoogleAJAXAPIの使用

呼び出し:

$.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);
      });
    }
  }
});

プリントアウト:

------------------------
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
于 2012-06-08T05:43:24.190 に答える
39

別の非推奨の (@daylightのおかげで)オプションであり、私にとって最も簡単です(これは私がSpokenToday.infoに使用しているものです):

JQueryを使用せず、2つのステップのみでGoogle FeedAPIを実行します。

  1. ライブラリをインポートします。

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">google.load("feeds", "1");</script>
    
  2. フィードの検索/読み込み(ドキュメント):

    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);
    });
    
  3. データを解析するには、応答形式に関するドキュメントを確認してください。

于 2013-06-13T02:03:04.367 に答える
4

rssウィジェット用のGoogleFeedAPIのシンプルで無料の代替手段を探している場合は、 rss2json.comがそのための適切なソリューションになる可能性があります。

以下 の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>

于 2018-06-04T14:17:18.560 に答える
4

これを読んでいる他の人(2019年以降)にとって、残念ながらほとんどのJSRSS読み取り実装は現在機能していません。まず、Google APIがシャットダウンしたため、これはオプションではなくなりました。CORSセキュリティポリシーにより、通常、RSSフィードをクロスドメインでリクエストすることはできません。

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.

これは正しく、エンドWebサイトによるセキュリティ上の予防措置ですが、上記の回答が機能しない可能性が高いことを意味します。

私の回避策は、おそらく、宛先フィード自体にアクセスしようとするのではなく、PHPを介してRSSフィードを解析し、JavaScriptが私のPHPにアクセスできるようにすることです。

于 2019-10-02T10:57:05.757 に答える
2

プレーンなJavaScriptAPIを使用する場合は、https://github.com/hongkiat/js-rss-reader/に良い例があります。

https://www.hongkiat.com/blog/rss-reader-in-javascript/での完全な説明

これは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'))
于 2018-09-09T05:43:41.117 に答える
2

私は多くの誤解を招く記事や回答に憤慨したので、自分のRSSリーダーを作成しました: https ://gouessej.wordpress.com/2020/06/28/comment-creer-un-lecteur-rss-en-javascript-how- to-create-a-rss-reader-in-javascript /

AJAXリクエストを使用してRSSファイルをフェッチできますが、CORSプロキシを使用している場合にのみ機能します。より堅牢なソリューションを提供するために、独自のCORSプロキシを作成してみます。それまでの間、動作します。DebianLinuxのサーバーにデプロイしました。

私のソリューションはJQueryを使用していません。サードパーティのライブラリを使用せずに、プレーンなJavascript標準APIのみを使用しており、Microsoft InternetExplorer11でも機能するはずです。

于 2020-06-28T12:42:24.500 に答える
0

jquery-rssまたはVanillaRSSを使用できます。これは、優れたテンプレートが付属しており、非常に使いやすいです。

// 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');
});

実用的な例については、 http://jsfiddle.net/sdepold/ozq2dn9e/1/を参照してください。

于 2019-10-16T10:23:31.327 に答える
0

これに対する適切な解決策を見つけようとして、jQueryFeedAPIを介してRSSおよびAtomフィードを解析および表示する優れた機能を実行するFeedEkjQueryRSS /ATOMフィードプラグインに出会いました。基本的なXMLベースのRSSフィードの場合、それは魅力のように機能し、ローカルでも実行するためにサーバー側のスクリプトやその他のCORS回避策を必要としないことがわかりました。

于 2019-11-11T16:26:49.200 に答える
0

受け取り続けたCORSエラーのため、jsだけでRSSを解析するための解決策が見つかりませんでした。プラグインをインストールすることは私にとってオプションではなく、プロキシを構築することも楽しくなく、私が見つけた小さなソリューションは機能しませんでした。

したがって、誰かがここに来てサーバー側を使用できる場合に備えて、PHPでこのソリューションが完璧に機能することを発見しました!(CORSエラーなし!「xはCORSポリシーによってブロックされました...」)

于 2021-09-01T22:28:24.100 に答える