我一直在尝试制作一个网页,向我展示我每天使用的各种东西。我尝试在那里获取 Reddit feed,它会每 x 秒(60 秒左右)自动刷新一次。但问题是提要是这样的
document.write({INSERT FEED HERE});
它是异步加载的,因此会出现错误:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
那么有没有什么办法可以让这个更新本身,而不需要更新整个页面。
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="reddit">
<script>
$(document).ready(
function() {
setInterval(function() {
reload_js();
}, 60000);
});
function reload_js() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://www.reddit.com/r/ProgrammerHumor/new/.embed?limit=10&t=all";
document.getElementById("reddit").appendChild(s);
}
</script>
</div>
</body>
这是我现在的 reddit feed 的简单页面。
最佳答案
默认情况下,如果未定义回调参数,.embed
Web 服务将使用 document.write
。
只需添加一个回调参数,就像这样 https://www.reddit.com/r/ProgrammerHumor/new/.embed?limit=10&t=all&callback=yourFunction
并添加一个 yourFunction
函数来附加内容
function yourFunction(data) {
document.getElementById("reddit").appendChild(data);
}
享受吧:)
关于javascript - 刷新 div 内容,其中包含将 feed 作为 document.write 获取的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39519815/