使用jQuery解析RSS

问题描述 投票:191回答:20

我想使用jQuery来解析RSS提要。这可以通过开箱即用的基础jQuery库完成,还是需要使用插件?

jquery jquery-plugins rss feedparser
20个回答
210
投票

警告

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

5
投票

I agree with @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>

4
投票

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>

2
投票

我正在使用jquery和yql作为feed。你可以用yql检索twitter,rss,buzz。我从http://tutorialzine.com/2010/02/feed-widget-jquery-css-yql/读到。这对我来说非常有用。


1
投票
<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>

1
投票

我建议你使用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'
});

0
投票

使用谷歌缓存的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>

0
投票

zRSSfeed建立在jQuery之上,简单的主题非常棒。 试试看。


0
投票

The jQuery-rss project非常轻巧,并没有强加任何特定的造型。

语法可以很简单

$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")

看到working example at http://jsfiddle.net/jhfrench/AFHfn/


-1
投票

jQuery Feeds是一个不错的选择,它有一个内置的模板系统并使用Google Feed API,因此它具有跨域支持。


-1
投票

Superfeedr有一个jquery plugin,非常好。您将不会遇到任何跨源策略问题,并且实时传播更新。


184
投票

Use jFeed - 一个jQuery RSS / Atom插件。根据文档,它很简单:

jQuery.getFeed({
   url: 'rss.xml',
   success: function(feed) {
      alert(feed.title);
   }
});

-2
投票

jFeed很简单,有一个example供你测试。但是,如果您要解析来自其他服务器的订阅源,则需要在订阅源服务器上允许使用Cross Origin Resource Sharing(CORS)。你还需要check browser support

我上传了the sample,但是当我通过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


155
投票

对于我们这些讨论较晚的人来说,从1.5开始,jQuery具有内置的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...
    });
});

16
投票

jFeed在IE中不起作用。

使用zRSSFeed。它有5分钟的工作时间


15
投票

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

15
投票

您还可以使用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/


9
投票

除非您的RSS数据是私有的,否则请使用Google AJAX Feed API。当然,这很快。

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


8
投票

更新[4/25/2016]现在更好的书面和完全支持的版本,在GitHub.jQRSS托管更多的选项和能力

我看了Selected AnswerNathan Strutz,然而,jQuery插件页面链接仍然关闭,该网站的主页似乎没有加载。我尝试了一些其他的解决方案,发现它们中的大多数都是,不仅过时了,而且很容易!因此,我把帽子扔到那里并制作了自己的插件,并且在这里有死链接,这似乎是一个提交答案的好地方。如果您在2012年(即2013年b)期待寻找这个答案,您可能会像我一样注意到死链接和旧建议的挫败感。下面是我的现代插件示例的链接以及插件的代码!只需将代码复制到JS文件中,并将其链接到您的标题中,就像任何其他插件一样。使用非常EZ!

jsFiddle

插件代码 2015年2月9日 - 在向命令发送命令之前进行了长期逾期更新以检查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('在此搜索单词而不是链接',函数(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.
        */
}

5
投票
(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>
© www.soinside.com 2019 - 2024. All rights reserved.