我需要解析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.
我需要的
解决方法
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标头……
<?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’标题”错误)