0

我正在尝试使用 JavaScript 的 setInterval 函数让 HTML 页面每秒使用文本文件中的内容更新文本区域。但是,setInterval 调用中的函数似乎只运行一次。

Javascript:

// Send a GET request to the given location
function sendRequest(location, nonblocking) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", location, nonblocking);
    xmlhttp.send();
    return xmlhttp.responseText;
}

// Refresh the communication log
function refreshLog() {
     document.getElementById("comm_log").value = sendRequest("src/log.txt", false);
}

window.setInterval(refreshLog, 1000);

请求不是异步的,因为文本文件永远不会很长,这是我试图快速整合的东西。

HTML:

<html>
<head>
<style type="text/css">
textarea {
    width: 98%;
    height: 80%;
    resize: none;
    font-family: "Courier New";
}
</style>

<script type="text/javascript" src="src/script.js"></script>

</head>

...

<textarea id="comm_log" readonly></textarea>

...

</html>

有人有想法吗?

4

1 回答 1

5

我想你的浏览器正在缓存。您只获取一次数据,然后从缓存中提供下一个请求。所以refreshLog应该重复调用,只是下面的调用不会对页面产生任何影响,因为它是从缓存中提供的。

在 URL 上附加一些独特的部分,例如?=<timestamp>.

xmlhttp.open("GET", location + '?=' + new Date().getTime(), nonblocking);
于 2013-06-26T17:33:22.730 回答