質問

jQueryを使用してRSSフィードを解析したい。これは基本のjQueryライブラリですぐに実行できますか、それともプラグインを使用する必要がありますか?

役に立ちましたか?

解決

警告

  

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

後半に議論する私たちにとって、jQueryには1.5からxml解析機能が組み込まれているため、プラグインやサードパーティサービスなしでこれを簡単に行うことができます。 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...
    });
});

jFeedはIEで動作しません。

zRSSFeed を使用します。 5分で動作しました

JFeedの使用

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>

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/jhfrench/AFHfn/ を参照してください。

RSSデータがプライベートでない限り、Google AJAX Feed APIを使用します。もちろん高速です。

https://developers.google.com/feed/

  

UPDATE [ 4/25/2016 ] GitHub.jQRSS

選択回答 Nathan Strutz ただし、jQueryプラグインページのリンクはまだダウンしており、そのサイトのホームページは表示されていないようです負荷。他のいくつかのソリューションを試してみましたが、それらのほとんどが時代遅れであるだけでなく、簡単であることがわかりました!したがって、私はそこに帽子を投げて、独自のプラグインを作成しました。ここにリンクが切れているので、これは答えを提出するのに最適な場所のようです。 2012年にこの回答を探している場合(b 2013に間もなく)、ここで私が行ったように、リンク切れや古いアドバイスのフラストレーションに気付くかもしれません。以下は、私の modern プラグインの例へのリンクとプラグインへのコードです!コードをJSファイルにコピーするだけです&amp;他のプラグインと同様にヘッダーにリンクします。使用は非常にEZ!

jsFiddle

  

プラグインコード
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){/ * do work * /}) // 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を使用することは、あなたがXMLの代わりにJSONを取得します。 Googleをプロキシとして使用する追加の利点は、データへの直接アクセスをブロックする可能性のあるサービスがGoogleを停止する可能性が低いことです。スキーレポートとコンディションデータを使用した例を次に示します。これには、すべての一般的な現実世界のアプリケーションがあります:1)サードパーティのRSS / XML 2)JSONP 3)希望どおりにデータを取得できない場合の文字列と文字列のクリーニング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の古いバージョンでのみ動作します。更新されてから2年が経ちました。

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>

フィードにyqlでjqueryを使用しています。 yqlでtwitter、rss、buzzを取得できます。 http://tutorialzine.com/2010/02/から読みましたfeed-widget-jquery-css-yql / 。とても便利です。

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

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

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

http://jsfiddle.net/jhfrench/AFHfn/ の実例を参照してください

jQuery Feeds は優れたオプションで、組み込みのテンプレートシステムがあり、 Google Feed API。したがって、クロスドメインサポートがあります。

Superfeedr には、 jqueryプラグインこれは非常にうまく機能します。 クロスオリジンポリシーの問題は発生せず、更新はリアルタイムで伝達されます。

jFeedは簡単で、テストするためのが用意されています。ただし、別のサーバーからフィードを解析している場合は、 Cross Origin Resource Sharing (CORS)フィードのサーバー。また、ブラウザのサポートを確認する必要があります。

サンプルをアップロードしましたが、IEからサポートを受けられませんでしたどのバージョンでも、例のURLをhttpプロトコル経由でexample.com/feed.rssのようなものに変更したとき。 IE 8以降ではCORSをサポートする必要がありますが、jFeedの例ではフィードをレンダリングしませんでした。

最善の策は、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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top