开发者

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

开发者 https://www.devze.com 2023-04-07 01:07 出处:网络
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

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. T开发者_如何学Gohe 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?


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.


After some more troubleshooting, it turns out the was a cross-domain XHR issue. It was working in Chrome because, by default, Chrome was allowing the script on all domains. I tweaked the headers so Chrome knew to only allow the proper domains, but Firefox disallows cross-domain on XHR regardless. This was fixed by simply switching to GM_xmlhttpRequest instead, which allows cross-domain in Firefox and, thankfully, which Chrome also supports.

Thanks for the help, folks!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号