nexus_2006
nexus_2006

Reputation: 754

XMLHttpRequest throws error responseXML = null, but content appears anyway

This is my first XMLHttpRequest attempt, and while it works (the content is loaded from the xml file, and displays correctly in the browser), Mozilla Console shows the error:

[15:05:54.147] TypeError: xmlTree is null @ http://127.0.0.1/scripts/firstExternal.js:37

I don't know how it can be null, if the content loads?

Here is the function, called from the window.onload event:

function getXML() {
    if (window.XMLHttpRequest) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = (function () {
            if (xhr.readyState = 4) {
                if (xhr.status = 200) {
                    var xmlTree = xhr.responseXML;
                    var container = document.getElementById("container");
error here:         var textList = xmlTree.getElementsByTagName("text");
                    for (var i = 0; i<textList.length; i++) {
                        var tempText = document.createTextNode(textList[i].textContent);
                        var tempElem = document.createElement("P");
                        tempElem.appendChild(tempText);
                        container.appendChild(tempElem);
                    }
                } else {
                    document.getElementById("container").innerHTML = xhr.status + " - " + xhr.statusText;
                }
            }
        });
        xhr.open("GET","/res/sample.xml",true);
        xhr.send();
    }
}

and the XML:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <text>This is a sentence.</text>
    <text>This is the second sentence.</text>
    <text>ain't one.</text>
    <text>More bric a brac</text>
    <text>Foo, bar, baz.  Fizzbuzz forever.</text>
</xml>

EDIT: The response header:

Date: Sat, 01 Feb 2014 23:31:03 GMT Server: Apache/2.2.22 (Ubuntu) Last-Modified: Sat, 01 Feb 2014 23:28:47 GMT Etag: "21d16-ed-4f160a6f67bb5" Accept-Ranges: bytes Content-Length: 237 Content-Type: application/xml

Upvotes: 0

Views: 170

Answers (1)

Quentin
Quentin

Reputation: 943220

Your tests to see if the readyState and status are OK are using assignments (=) instead of equality tests (===).

Consequently, they are always true, so the contents of the if are run every time the readyState changes.

The last time they run, they are 4 and 200, so the right data appears.

Every previous time, you'll get an error.

Upvotes: 2

Related Questions