XMLHttpRequest for JSON file works perfectly in Chrome, but not in Firefox

gilrain picture gilrain · Sep 25, 2011 · Viewed 7.8k times · Source

I've narrowed my problem area down to the function below. It's part of a userscript I'm writing. It works perfectly in Chrome, but doesn't work at all in Firefox/Greasemonkey. I've tinkered with it all day and have hit a brick wall. The only thing that makes sense is if JSON.parse isn't working right, which would make sense since Chrome is known to handle JSON.parse somewhat differently... but I know the JSON is perfectly formed!

function getTagline() {
    var jsonfile = new XMLHttpRequest();
    jsonfile.open("GET", "http://example.com/somegood.json", true);
    jsonfile.onreadystatechange = function() {
        if (jsonfile.readyState == 4) {
            if (jsonfile.status == 200) {
                var taglines = JSON.parse(jsonfile.responseText);
                var choose = Math.floor(Math.random() * taglines.length);
                var tagline = document.createTextNode(taglines[choose].metais);
                insertTagline(tagline);
            }
        }
    };
    jsonfile.send(null);
}

Any ideas?

Answer

Ramzi Khahil picture Ramzi Khahil · Sep 25, 2011

I was told that JSON is not supported without an extra library, see here the accepted answer. I also tried this

try {
    clientList = JSON.parse(responseText);
} catch (e) {
    alert(e.message);
}

And the message I get is "JSON is undefined". So the answer seems correct.