0

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>
3
  • It's bad form to use document.write(). Commented Feb 13, 2013 at 7:28
  • Using document.write() after the page has been parsed is very fatal ; ). Commented Feb 13, 2013 at 7:40
  • I'm just trying to get something quick and dirty printed on the page from the XML. Is the script (and thus the document.write()) not parsed before the HTML below it? That code lives within <HEAD></HEAD> Commented Feb 13, 2013 at 18:47

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It's great to have an understanding of what's going on, even for poor form functions like document.write().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.