我有一个表有一个事务列表,我试图按设定的时间间隔更新表内容。我在linux red hat服务器上运行此页面。这只是AJAX现在无法正常工作。
<!doctype html>
<html>
<head>
<script>
function updateTrans() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.HTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("transactions").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "update_trans.txt", true);
xmlhttp.send();
}
window.setInterval(updateTrans(), 4000);
</script>
<link href="trans_styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 id="heading"> Chomp The Bit </h1>
<div id="transactions">
<table id="trans_tbl" border="0">
<tr>
<th colspan="2">Latest Transactions</th>
</tr>
<tr>
<td>aaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>
<td>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>
</tr>
<tr>
<td>bbbbbbbbbbbbbbbbbbbbbbbbbbbbb</td>
<td>bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb</td>
</tr>
<tr>
<td>ccccccccccccccccccccccccccccc</td>
<td>cccccccccccccccccccccccccccccc</td>
</tr>
<tr>
<td>ddddddddddddddddddddddddddddd</td>
<td>dddddddddddddddddddddddddddddd</td>
</tr>
<tr>
<td>eeeeeeeeeeeeeeeeeeeeeeeeeeeee</td>
<td>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee</td>
</tr>
<tr>
<td>fffffffffffffffffffffffffffff</td>
<td>ffffffffffffffffffffffffffffffff</td>
</tr>
<tr>
<td>ggggggggggggggggggggggggggggg</td>
<td>gggggggggggggggggggggggggggggggg</td>
</tr>
<tr>
<td>hhhhhhhhhhhhhhhhhhhhhhhhhhhhh</td>
<td>hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh</td>
</tr>
<tr>
<td>iiiiiiiiiiiiiiiiiiiiiiiiiiiiii</td>
<td>iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii</td>
</tr>
<tr>
<td>jjjjjjjjjjjjjjjjjjjjjjjjjjjjjj</td>
<td>jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj</td>
</tr>
</table>
</div>
</body>
</html>
答案 0 :(得分:0)
确保在同一目录中包含update_trans.txt
文件,并且该文件不为空。
<head>
<script>
function updateTrans() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.HTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("transactions").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "update_trans.txt", true);
xmlhttp.send();
}
window.setInterval(updateTrans(), 4000);
</script>
<link href="trans_styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 id="heading"> Chomp The Bit </h1>
<div id="transactions">
</div>
</body>
</html>
答案 1 :(得分:0)
我不确定这是否可以解决问题,但您应该window.setInterval(updateTrans, 4000)
而不是window.setInterval(updateTrans(), 4000)
。也就是说,你应该将对函数的引用作为setInterval
的第一个参数传递,而不是调用函数的返回值,这是你在当前代码中所做的。在您当前的代码中,updateTrans
将被调用一次 - 当您自己调用它时 - 但不会像您想要的那样每4000ms调用一次。
我还建议您使用setTimeout
代替setInterval
- 我写了a post about this。