0

我认为我的脚本中存在某种非致命错误,它不允许我使用 Firebug 和 b/ 调试脚本,导致 Firefox 在我在页面上时不断显示连接...(带有漩涡) . 该脚本似乎运行良好。

有什么想法可能导致这种情况吗?

<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>
4

1 回答 1

1

您页面中的所有代码都已解析,但在页面完成之前不会执行。发生这种情况,因为您是document.write()onreadystatechange事件处理函数调用而不是解析时间。

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
于 2013-02-14T06:08:21.857 回答