我有一个加载 RSS 新闻源的网站 http://www.tagesschau.de/xml/rss2
我想每 60 秒检查一次 RSS 提要是否已更新。如果已更改,则应重新加载 RSS 提要。对于 Ajax,我认为它会很好用,尽管我被困在这里:
<script type="text/javascript" src="../js/jquery.ajax-cross-origin.min.js"></script>
<script type="text/javascript">
function checkRSS() {
$.ajax({
crossOrigin: true,
type: 'GET',
proxy: "../php/proxy.php",
url: "http://www.tagesschau.de/xml/rss2",
dataType: "xml",
success: function (xml) {
//console.log(xml);
},
error: function(xml) {
console.log(xml);
}
});
}
setInterval("checkRSS()", 60000);
</script>
(我评论了 success
事件 console.log
以查看 Ajax 是否会触发 success
或 error
事件。它触发了 error
事件。)
在控制台中,我得到 status: 200
、readyState: 4
和 statusText: "success"
。
有人知道为什么会触发 error
事件吗?我通过http://jsonlint.com检查了url 。它确实加载了列表,但给了我一个错误。这是问题吗?
Ajax 跨源插件:http://www.ajax-cross-origin.com/how.html#js-what-is-this-plugin
编辑
我从 Ajax-Cross-Origin plugin 添加了一个代理 php 文件(并在上面的 Ajax 代码中添加了其链接):
<?php
$url = (isset($_GET['url'])) ? $_GET['url'] : false;
if(!$url) exit;
$referer = (isset($_SERVER['HTTP_REFERER'])) ? strtolower($_SERVER['HTTP_REFERER']) : false;
$is_allowed = $referer && strpos($referer, strtolower($_SERVER['SERVER_NAME'])) !== false;
$string = ($is_allowed) ? utf8_encode(file_get_contents($url)) : 'You are not allowed to use this proxy!';
$json = json_encode($string);
$callback = (isset($_GET['callback'])) ? $_GET['callback'] : false;
if($callback){
$jsonp = "$callback($json)";
header('Content-Type: application/javascript');
echo $jsonp;
exit;
}
echo $json;
?>
也许是一个愚蠢的问题,但我应该将 HTTP_REFERER
和 SERVER_NAME
更改为某些内容吗?
现在发生的情况是,success
事件被触发 - 是!- 但其日志的结果仅包含 ""
。
最佳答案
跨站点脚本策略将使这变得棘手......您最好的选择可能是使用第三方 API,例如 Superfeedr或 Google Feed API。 这样做的好处是,它们将处理您的负载,并且仍然能够很快地从原始提要中检索更新。
关于javascript - 使用 Ajax 检查跨域 RSS 是否已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31383822/