开发者

Function fails on the second time i call it

this is my code:

 <script language="javascript">
    function refresh() {
        try {
            xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {}
        xmlhttp.onreadystatechange = triggered;
        xmlhttp.open("GET", "data.php");
        xmlhttp.send(null);
    }

    function triggered() {
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
            document.getElementById("ins").innerHTML = xmlhttp.responseText;
        }
        document开发者_运维技巧.getElementById("loading").style.display = "block";
    }
</script>

<a href="javascript:refresh();">Refresh List</a>

The functions fails on the second time i call it,

Error: document.getElementById("loading") is null

Very strange, any fix for it?


Is it possible that loading is a child of ins and is overwritten by triggered()?


Move the loading div from outside of the ins div:

<div id="loading"></div>  
<div id="ins"></div>  

and change the javascript to the following:

function triggered() {  
    if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {  
        document.getElementById("ins").innerHTML = xmlhttp.responseText;  
    }  
    document.getElementById("loading").style.display =  
                (xmlhttp.readyState == 4) ? "none" : "block";
}  

This will hide the loading div for you when you finish and will re-show it next time you invoke this method.


I'm not an expert on JavaScript, but I guess:

The call to document.getElementById("loading") is not limited to xmlhttp.readyState==4.

It is called for all readyStates from 0 to 4. If the line

document.getElementById("ins").innerHTML = xmlhttp.responseText;

makes significant changes to the page (probably "remove" the element "loading"), the following

document.getElementById("loading").style.display = "block";

leads to an error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜