Non-Fatal Javascript Error?

南笙酒味 提交于 2019-12-24 20:25:15

问题


I think there's some kind of non-fatal bug in my script that's not allowing me to a/ debug the script with Firebug and b/ causes Firefox to constantly display a Connecting... (with the swirly) while I'm on the page. The script seems to run fine though.

Any ideas what could cause that?

<script type="text/javascript">
var xmlHttp;
var xmlDoc;

loadXMLFile();

function loadXMLFile()
{
    xmlHttp = new window.XMLHttpRequest();
    xmlHttp.open("GET", "myFile.xml", true);
    xmlHttp.onreadystatechange = StateChange;
    xmlHttp.send(null);
}

function StateChange()
{
    if ( xmlHttp.readyState == 4 )
    {
        xmlDoc = xmlHttp.responseXML;
        processXML();
    }
}

function processXML()
{
    var firstNames = xmlDoc.querySelectorAll("name");
    if (firstNames == null)
    {
        document.write("Oh poo. Query selector returned null.");
    }
    else
    {
        for (var i = 0; i < firstNames.length; i++)
        {
            document.write(firstNames[i].textContent + "<br>");
        }
    }
}
</script>

回答1:


All the code in your page is parsed, but not executed before the page is completed. This happens, since you're calling document.write() from onreadystatechange event handler function rather than parsing time.

In this case document.write() implicitly calls document.open(), which wipes all the code out of the page, and only what is left is the text written by document.write(). Also document is left open, which causes the browser being "busy". This can be avoided by using document.close(), but it won't prevent the original content to vanish.

You need to add an element to the body and then use some "real" DOM manipulation method. Something like this:

<div id="qResult"></div>

Then instead of document.write():

document.getElementById('qResult').innerHTML = WHAT_EVER_NEEDED


来源:https://stackoverflow.com/questions/14848440/non-fatal-javascript-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!