我在使用 jQuery 检索位于外部域的 RSS 提要时遇到了问题。它在 Safari 中工作,但其他浏览器会因为同源策略限制而出错(这也记录在 $.ajax() 函数中)。
想知道我是怎么修的吗?
我在使用 jQuery 检索位于外部域的 RSS 提要时遇到了问题。它在 Safari 中工作,但其他浏览器会因为同源策略限制而出错(这也记录在 $.ajax() 函数中)。
想知道我是怎么修的吗?
我制作了一个简单的 PHP 脚本,如下所示:
<?php
/*
fetch.php fixes this issue: http://en.wikipedia.org/wiki/Same_origin_policy
Read more:
* http://api.jquery.com/jQuery.ajax/
* http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed-by-access-control-allow-origin
* http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains
*/
// Requires URL
if ( !isset($_REQUEST['url']) || empty($_REQUEST['url']) ) exit( 'No url specified' );
// Set content-type
$type = 'application/rss+xml; charset=utf-8;';
if ( isset($_REQUEST['type']) && !empty($_REQUEST['type']) ) {
$type = urldecode($_REQUEST['type']);
}
// Adapted from http://www.howtogeek.com/howto/programming/php-get-the-contents-of-a-web-page-rss-feed-or-xml-file-into-a-string-variable/
function get_url_contents( $url ){
if ( function_exists('curl_init') ) {
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL, $url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
} else {
return file_get_contents( $url );
}
return 'Could not retrieve url';
}
// Output content from url
header( 'Content-type: ' . $type );
echo get_url_contents( urldecode($_REQUEST['url']) );
?>
它看起来很垃圾,但目前效果很好。我希望它有所帮助。