微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用JavaScript(外部域)解析RSS源?

我需要解析RSS提要并在HTML页面显示已解析的详细信息.

找到的解决方

How to parse an RSS feed using JavaScript?一个非常相似的问题,我跟着它.

使用上面的问题,我构建了以下代码.

<script>
  $(document).ready(function() {
    //Feed to parse
    var Feed = "https://Feeds.Feedburner.com/raymondcamdensblog?format=xml";

    $.ajax(Feed,{
        accepts:{
            xml:"application/RSS+xml"
        },dataType:"xml",success:function(data) {
            //Credit: https://stackoverflow.com/questions/10943544/how-to-parse-an-RSS-Feed-using-javascript

            $(data).find("item").each(function () { // or "item" or whatever suits your Feed
                var el = $(this);
                document.write("------------------------");
                document.write("title      : " + el.find("title").text());
                document.write("link       : " + el.find("link").text());
                document.write("description: " + el.find("description").text());
            });


        }   
    });

});
</script>

错误

Failed to load
07001: No
‘Access-Control-Allow-Origin’ header is present on the requested
resource. Origin ‘07002’ is therefore not allowed access.

我需要的

如何更改我的代码以使用JavaScript读取RSS源而不会出现上述错误

解决方法

由于 same-origin policy,您收到了该错误.请参阅下文和/或阅读 MDN的完整文章

For security reasons,browsers restrict cross-origin HTTP requests
initiated from within scripts. For example,XMLHttpRequest and the
Fetch API follow the same-origin policy. This means that a web
application using those APIs can only request HTTP resources from the
same origin
the application was loaded from,unless the response
from the other origin includes the right CORS headers.

所以你的脚本正在制作一个跨源HTTP请求(通过jQuery.ajax()使用XMLHttpRequest)到https://feeds.feedburner.com/raymondcamdensblog?format=xml,但是FeedBurner没有设置Access-Control-Allow-Origin的CORS头,因此你得到了“失败”加载……“错误. (但即使标题已设置,如果它不包含您的来源(localhost或some-domain.com),您仍会得到相同的错误.)

那么如何更改代码以使用JavaScript读取RSS源而不会出现该错误

>使用第三方Web服务,就像@ Saeed建议的那样.
>创建一个服务器端脚本(例如,使用PHP),该脚本获取内容并向该脚本发出AJAX请求,而不是直接从FeedBurner或实际源URL请求它.请参阅下面的简单示例.
>如果我真的不得不这样做,我可能会要求FeedBurner设置合适的CORS标头……

用于获取Feed内容的非常简单的PHP脚本示例:

<?PHP
// Set the Feed URL.
$Feed_url = 'https://Feeds.Feedburner.com/raymondcamdensblog?format=xml';

// Fetch the content.
// See http://PHP.net/manual/en/function.file-get-contents.PHP for more
// information about the file_get_contents() function.
$content = file_get_contents( $Feed_url );

// Set the Content-Type header.
header( 'Content-Type: application/RSS+xml' );

// display the content and exit.
echo $content;
exit;
?>

例如,您可以将其保存到fetch-Feed.PHP,然后在JavaScript / jQuery脚本代码中,更改Feed变量的值,如下所示:

var Feed = "http://localhost/path/to/fetch-Feed.PHP";

这样(即使用您自己的服务器端脚本),您至少可以确保浏览器始终授予您的XMLHttpRequest(或AJAX)请求. (即你不会得到“No’Access-Control-Allow-Origin’标题错误)

原文地址:https://www.jb51.cc/js/157956.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐