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

I narrowed my problem area down to the function below. This is part of the custom text that I am writing. It works fine in Chrome, but doesn't work at all in Firefox / Greasemonkey. I fiddled with him all night and hit a brick wall. The only thing that makes sense is that JSON.parse is not working correctly, which makes sense since Chrome, as you know, handles JSON.parse a little differently ... but I know that 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?

+7
source share
2 answers

After resolving some problems, it turned out that this is a cross-domain XHR problem. It worked in Chrome, since by default Chrome allowed a script for all domains. I changed the headers, so Chrome knew that only domains were allowed, but Firefox forbids cross-domain transfers to XHR. This was fixed by simply switching to GM_xmlhttpRequest, which allows cross-domain in Firefox and, fortunately, Chrome also supports it.

Thanks for the help guys!

+1
source

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

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

And the message I get is "JSON is undefined". Therefore, the answer seems to be correct.

+1
source

All Articles