문제

을 사용하고 싶 jQuery 분석 RSS feeds.과 함께 할 수있는 기본 jQuery 라이브러리의 상자 또는 내가 필요한 것을 사용하여 플러그인?

도움이 되었습니까?

해결책

경고

Google 피드 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);
   }
});

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

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 피드 API를 사용하십시오. 물론 빠릅니다.

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

업데이트 [4/25/2016] 이제 더 많은 옵션과 능력이있는 더 나은 서면 및 완전 지원 버전 github.jqrss

나는 봤다 선택된 대답 ~에 의해 Nathan Strutz, 그러나 jQuery 플러그인 페이지 링크가 여전히 다운되었고 해당 사이트의 홈페이지는로드되지 않은 것 같습니다. 나는 몇 가지 다른 솔루션을 시도했고 대부분의 솔루션을 찾았습니다. 쉬운! 그래서 나는 내 모자를 내밀어 내 자신의 플러그인을 만들었고, 여기에 죽은 링크가 있으면 답을 제출하기에 좋은 장소 인 것 같습니다. 2012 년 에이 답변을 찾고 있다면 (2013 년까지 곧) 죽은 링크와 오래된 조언에 대한 좌절감을 알 수 있습니다. 아래는 내 링크입니다 현대의 플러그인 예제 및 플러그인의 코드! 코드를 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 ( '링크 대신 여기에 검색어', 함수 (피드) { / * 작업 * /}) // 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) 원하는 방식으로 정확하게 데이터를 얻을 수 없을 때 문자열 및 스트링을 배열로 정리합니다. 4)로드에 요소를 추가합니다. 돔 이것이 어떤 사람들에게 도움이되기를 바랍니다!

<!-- 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 DOCS의 빠른 예입니다.

<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 공급 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 Ajax API, Google과 원하는 모든 출력 형식으로 캐시했습니다.

코드 샘플;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")

a http://jsfiddle.net/jhfrench/afhfn/의 작업 예제

jQuery 피드 좋은 옵션이며, 템플릿 템플릿 시스템이 내장되어 있으며 Google Feed API를 사용하므로 크로스 도메인 지원이 있습니다.

Superfeedr a jQuery 플러그인 그것은 아주 잘합니다. 교차 출신 정책 문제가 없으며 업데이트는 실시간으로 전파됩니다.

Jfeed는 쉽고 예시 당신이 테스트하기 위해. 그러나 다른 서버에서 피드를 구문 분석하는 경우 허용해야합니다. 교차 원산지 자원 공유 피드의 서버에서 (CORS). 당신은 또한 필요합니다 브라우저 지원을 확인하십시오.

나는 업로드했다 샘플 그러나 예제의 URL을 HTTP 프로토콜을 통해 example.com/feed.rss와 같은 것으로 변경했을 때 여전히 IE의 지원을받지 못했습니다. CORS는 IE 8 이상을 지원해야하지만 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