Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用jQuery解析RSS_Jquery_Jquery Plugins_Rss_Feedparser - Fatal编程技术网

用jQuery解析RSS

用jQuery解析RSS,jquery,jquery-plugins,rss,feedparser,Jquery,Jquery Plugins,Rss,Feedparser,我想使用jQuery解析RSS提要。这可以用现成的基本jQuery库来完成吗?或者我需要使用插件吗?-jQuery RSS/Atom插件。根据文档,它非常简单: jQuery.getFeed({ url: 'rss.xml', success: function(feed) { alert(feed.title); } }); 除非您的RSS数据是私有的,否则请使用GoogleAjax提要API。当然,速度很快 函数getFeed(发送方,uri){ jQuer

我想使用jQuery解析RSS提要。这可以用现成的基本jQuery库来完成吗?或者我需要使用插件吗?

-jQuery RSS/Atom插件。根据文档,它非常简单:

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

除非您的RSS数据是私有的,否则请使用GoogleAjax提要API。当然,速度很快

函数getFeed(发送方,uri){ jQuery.getFeed({ url:'proxy.php?url='+uri, 成功:功能(提要){ jQuery(发送方).append(“” + '' + ''); var html=''; 对于(变量i=0;i

函数loadFeed(){
$.getFeed({
url:'url=http://sports.espn.go.com/espn/rss/news/',
成功:功能(提要){
//头衔
$('#result')。追加('+'');
//无序列表
var html='
    '; $(feed.items)。每个(函数(){ 变量$item=$(此项); //跟踪($item.attr(“链接”); html+='
  • '+ ' ' + “”+$item.attr(“说明”)+“

    ”+ //“”+$item.attr(“c:date”)+“

    ”+ “
  • ”; }); html+='
'; $('#result').append(html); } }); }
我正在使用jquery和yql作为提要。您可以使用yql检索twitter、rss和buzz。我读了一本书。它对我非常有用。

jFeed有些过时,只使用较旧版本的jQuery。更新至今已有两年

zRSSFeed的灵活性可能稍差一些,但它易于使用,并且可以与当前版本的jQuery(目前为1.4)一起使用

以下是zRSSFeed文档中的一个快速示例:

<div id="test"><div>

<script type="text/javascript">
$(document).ready(function () {
  $('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {
    limit: 5
  });
});
</script>

$(文档).ready(函数(){
$('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {
限额:5
});
});

jFeed在IE中不起作用


使用。让它在5分钟内工作

警告

已正式弃用且不再有效


不需要整个插件。这将把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);
    }
  });
}

对于我们这些讨论较晚的人来说,从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...
    });
});
,使用Google是一种可靠的、可重用的方法,它带来了巨大的好处,让您重新获得JSON而不是XML。使用谷歌作为代理的另一个优势是,可能阻止您直接访问其数据的服务不太可能阻止谷歌。下面是一个使用ski报告和条件数据的示例。这有所有常见的现实世界应用程序: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>

功能显示报告(feedResponse){
//获取滑雪报告内容字符串
var itemString=feedResponse.entries[0]。内容;
var publishedDate=feedResponse.entries[0]。publishedDate;
//根据需要手动清理字符串
itemString=itemString.replace(“主要:不适用”,“前期条件”);
publishedDate=publishedDate.substring(0,17);
//从字符串解析ski报告数据
var itemsArray=itemString.split(“/”);
//构建无序列表
var html=''+feedResponse.entries[0]。title+'';
html+='
    '; html+='
  • 滑雪状态:'+itemsArray[0]+'
  • ; //最后48小时 html+='
  • '+itemsArray[1]+'
  • '; //雪况 html+='
  • '+itemsArray[2]+'
  • '; //底深 html+='
  • '+itemsArray[3]+'
  • '; html+='
  • 滑雪报告日期:'+publishedDate+'
  • '; html+='
'; $('body').append(html); } 函数parseRSS(url,回调){ $.ajax({ url:document.location.protocol+'//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q='+encodeURIComponent(url), 数据类型:“json”, 成功:功能(数据){ 回调(data.responseData.feed); } }); } $(文档).ready(函数(){ //滑雪报告 parsers(“http://www.onthesnow.com/michigan/boyne-highlands/snow.rss“、报告); });
基于jQuery构建,简单的主题非常棒。
试试看

更新(2019年10月15日)

我将核心逻辑从jquery rss提取到一个名为的新库中,该库使用fetch API,无需任何其他依赖项即可工作:

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

原创的

职位:

您还可以使用,它具有很好的模板,非常易于使用:

$("#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>'
})
$(“#你的div”).rss(“http://www.recruiter.com/feed/career.xml", {
限额:3,,
layoutTemplate:“
    {entries}
”, 入口模板:“

  • {shortBodyPlain}
  • ” })
    收益率(截至2013年9月18日):

    
    

    • 求职者往往对招聘人员和招聘经理有某种“恐惧”,我指的是敬畏和尊重

    • 很久以前就处理过“完美res”
      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');
      });
      
      
      $("#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>'
      })
      
      <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>
      
      (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>
      
      <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>
      
      (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 */ })
      
      {
          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.
              */
      }
      
      $("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")
      
      $('#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'
      });