0

此脚本每半秒抛出一次此错误:

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

这是 signal.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();

}
4

2 回答 2

0

您需要首先检查是否req.readyState等于4(means 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 文档

于 2013-10-22T15:01:35.770 回答
0

先检查req.readyState是否为4,再检查req.status是否为200。HTTP状态码在请求处理之前没有设置,所以在readyState为4之前不能使用。

您可以查看此链接以获取有关 onreadystatechange 事件的更多信息。

于 2013-10-21T16:28:18.430 回答