此脚本每半秒抛出此错误:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. signals.js:9
req.onreadystatechange signals.js:9
update_table signals.js:26
req.onreadystatechange
这是signals.js - 我希望它每5秒重新加载一次,如果有新内容,则触发“声音”警报。
function update_table()
{
var old_table = document.getElementById('signals').innerHTML;
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.status == 200)
{
if(req.readyState == 4)
{
var new_table = req.responseText;
alert(old_table);
alert(new_table);
if(old_table != new_table)
{
//play sound
alert("Sound!");
}
alert("Refresh!");
setTimeout(update_table, 5000);
}
}
}
var link = "table.php?refresh=true";
req.open("GET", link, false);
req.send();
}
答案 0 :(得分:0)
首先检查req.readyState是否等于4,然后检查req.status是否等于200。 在处理请求之前未设置HTTP状态代码,因此在readyState等于4之前不能使用它。
您可以查看this link以获取有关onreadystatechange事件的更多信息。
答案 1 :(得分:0)
您需要先检查req.readyState
是否等于4
(表示DONE
),然后才检查req.status
:
function update_table() {
var old_table = document.getElementById('signals').innerHTML;
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
// Here: first check for readyState
if(req.readyState === 4 && req.status == 200) {
var new_table = req.responseText;
alert(old_table);
alert(new_table);
if(old_table != new_table)
{
//play sound
alert("Sound!");
}
alert("Refresh!");
setTimeout(update_table, 5000);
}
}
var link = "table.php?refresh=true";
req.open("GET", link, false);
req.send();
}
有关详细信息,请参阅XMLHttpRequest doc。