2015-05-19 35 views
0

我在使用自定义代码获取Feed时遇到了XML URL的问题。 我试图了解它在谷歌和这里的解决方案,但我无法完全理解解决这个问题,所以我需要你的帮助,谢谢。jQuery和XML-无法读取远程资源

错误我得到了“跨源请求被阻止:同源策略不允许在http://www.straitstimes.com/news/sport/rss.xml处读取远程资源(原因:缺少CORS头'Access-Control-Allow-Origin')。”

那么,如何在我的代码下面实现解决方案?

$.ajax({ 
    type: 'GET', 
    url: 'http://www.straitstimes.com/news/sport/rss.xml', 
    contentType: "text/xml", 
    success: function (xml) { 
     $(xml).find("item").each(function() { 
      var title = $(this).find("title").text(); 
      var description = $(this).find("description").text(); 
      var linkUrl = $(this).find("link_url").text(); 
      var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>"; 
      $('#feedContainer').append('<article><h3>'+title+'</h3><p>'+description+link+'</p>'); 
     }); 
    }, 
     error : function (xhr, ajaxOptions, thrownError){ 
     console.log(xhr.status);   
     console.log(thrownError); 
    } 
}); 
+0

由于这是一个跨域请求,请检查该提要是否接受JSONP –

+0

我同意您的建议,但这段时间我必须使用XML。 – smile

回答

1

使用YQL控制台,我们可以克服这个交叉起源的请求......只是改变了URL和去除的contentType ..看看这个链接的jsfiddle

http://jsfiddle.net/1rmk8z4k/

$.ajax({ 
type: 'GET', 
url: 'http://query.yahooapis.com/v1/public/yql?q=select * from xml where url ="http://www.thestar.com.my/RSS/News/Education/"', 

success: function (xml) { 
    $(xml).find("item").each(function() { 
     var title = $(this).find("title").text(); 
     var description = $(this).find("description").text(); 
     var linkUrl = $(this).find("link_url").text(); 
     var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>"; 
     $('#feedContainer').append('<article><h3>'+title+'</h3><p>'+description+link+'</p>'); 
    }); 
}, 
    error : function (xhr, ajaxOptions, thrownError){ 
    console.log(xhr.status);   
    console.log(thrownError); 
} 
}); 
+0

谢谢@Ramanathan Muthuraman,它的工作完美.. – smile