JSON 文件的 XMLHttpRequest 在 Chrome 中完美运行,但在 Firefox 中则不行
我已将问题范围缩小到下面的函数。这是我正在编写的用户脚本的一部分。它在 Chrome 中完美运行,但在 Firefox/Greasemonkey 中根本不起作用。我一整天都在修补它,但碰壁了。唯一有意义的是 JSON.parse 是否无法正常工作,这是有意义的,因为众所周知 Chrome 处理 JSON.parse 的方式有所不同......但我知道 JSON 的格式是完美的!
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);
}
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有人告诉我,如果没有额外的库,则不支持 JSON,请参阅 这里接受的答案。我也尝试过这个
,我收到的消息是“JSON 未定义”。所以答案似乎是正确的。
I was told that JSON is not supported without an extra library, see here the accepted answer. I also tried this
And the message I get is "JSON is undefined". So the answer seems correct.
经过更多排查后,发现这是一个跨域 XHR 问题。它可以在 Chrome 中运行,因为默认情况下,Chrome 允许在所有域上使用该脚本。我调整了标头,这样 Chrome 就知道只允许正确的域,但 Firefox 无论如何都不允许 XHR 上的跨域。只需切换到 GM_xmlhttpRequest 即可解决此问题,该请求允许 Firefox 中的跨域,值得庆幸的是,Chrome 也支持跨域。
感谢各位的帮助!
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!