使用jQuery解析RSS

And*_*uhl 192 rss jquery jquery-plugins feedparser

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

And*_*lds 208

警告

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);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个好的答案.它依赖于第三方公司[Google]维护其服务.它没有回答原始问题("使用jQuery解析RSS")而是广告谷歌.如果Google删除或修改了他们的ajax API怎么办?你的网站坏了. (39认同)
  • 这是迄今为止最好的答案.jFeed不起作用. (32认同)
  • 请注意...使用谷歌API,饲料被缓存,所以你不会得到最新和最好的饲料. (15认同)
  • @CharlesGoodwin谷歌刚刚删除了这个API!https://developers.google.com/feed/?hl=en (11认同)
  • 试过jFeed它没有用,这个工作正常,不需要额外的库. (4认同)
  • 缓存在哪里?我该如何删除缓存? (3认同)
  • @CharlesGoodwin,是的,这个解决方案依赖于第三方托管的服务,因此并不理想,但如果您要访问跨域URL,则需要某种托管服务.根据Google的ToS(http://developers.google.com/feed/terms),此API将于2015年4月推出.雅虎也提供服务(请参阅https://github.com/AIRSHP/Feed-To- JSON/blob/master/jquery.feedToJSON.js),如果你想托管自己的,那么github上有很多XML-to-JSON项目. (2认同)

Nat*_*utz 185

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

jQuery.getFeed({
   url: 'rss.xml',
   success: function(feed) {
      alert(feed.title);
   }
});
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此插件的最新版本可用**[在Github上](https://github.com/jfhovinne/jFeed)**. (100认同)
  • Anirudha,也许你可以试试7-zip?它是免费的,开源的,并打开各种文件类型,包括tar/gzip. (12认同)
  • 注意:下载中包含各种很好的示例 (3认同)
  • 似乎不再主动维护jFeed(注释的最后一次更改是2年,并且许多打开拉请求似乎被忽略),并且不适用于最近发布的jQuery. (3认同)
  • 现实世界的任何使用例子?即解析和显示而不是警报.或者它就像$("#results")一样简单.addnd(feed.title) (2认同)

Dav*_*ond 158

对于我们这些讨论较晚的人来说,从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...
    });
});
Run Code Online (Sandbox Code Playgroud)

  • @jackocnr,是的,这是这种方法的缺点.除非您有权在源服务器上设置Access-Control-Allow-Origin标头,否则无法执行跨域请求.如果服务器支持jsonp,那么这是你最好的选择.否则,您可以使用域中的代理脚本来检索xml,然后调用该脚本而不是外部服务器. (12认同)
  • XmlHttpRequest错误:Access-Control-Allow-Origin不允许使用Origin (10认同)
  • 凉.jquery 1.5+的力量.不需要额外的插件. (2认同)

Mar*_*les 16

jFeed在IE中不起作用.

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

  • BTW,zRssFeed在内部使用[Google Feed RSS API](http://code.google.com/apis/feed/v1/jsondevguide.html).因此,如果想要自己进行HTML布局,那么直接查看它就更容易了. (3认同)
  • 可在http://www.zazar.net/developers/zrssfeed/上找到.关于自己尝试看看它是怎么回事,看起来很有希望. (2认同)
  • 仅供参考使用此插件的人.开发者发布了以下内容."此插件已中断由于Google Feeds API已从服务中删除,该插件已回复,因此将不再提供或支持." 资料来源:http://www.zazar.net/developers/jquery/zrssfeed/ (2认同)

And*_*uhl 15

使用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>
Run Code Online (Sandbox Code Playgroud)


sde*_*old 15

你也可以使用jquery-rss,它具有很好的模板,并且非常易于使用:

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

Run Code Online (Sandbox Code Playgroud)

收益率(截至2013年9月18日):

$("#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>'
})
Run Code Online (Sandbox Code Playgroud)

有关工作示例,请参见http://jsfiddle.net/jhfrench/AFHfn/.


yog*_*man 9

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

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


SpY*_*3HH 8

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

我看到所选答案弥敦道Strutz,然而,jQuery插件页面链接仍然向下,似乎该网站的主页上没有加载.我尝试了一些其他的解决方案,发现其中大部分是,不仅不合时宜,但EASY!因此,我把帽子扔到那里并制作了自己的插件,并且在这里有死链接,这似乎是一个提交答案的好地方.如果您在2012年(即2013年b)期待寻找这个答案,您可能会像我一样注意到死链接和旧建议的挫败感.下面是我的现代插件示例的链接以及插件的代码!只需将代码复制到JS文件中,并将其链接到您的标题中,就像任何其他插件一样.使用非常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);
Run Code Online (Sandbox Code Playgroud)

使用

//  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 */ })
Run Code Online (Sandbox Code Playgroud)

$ .jQRSS('在这里搜索单词而不是链接',函数(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.
        */
}
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用,而jFeed给了501. + 1 (2认同)
  • 很好!完美运作!胖插件回家了! (2认同)

Dyl*_*ade 5

我同意@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>
Run Code Online (Sandbox Code Playgroud)

  • 由于跨域问题,这不起作用.你需要JSONP. (2认同)

Joh*_*lia 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>
Run Code Online (Sandbox Code Playgroud)