我已经将问题范围缩小到下面的函数。这是我写的用户脚本的一部分。它在Chrome中工作完美,但在Firefox/Greasemonkey中根本不起作用。我整天都在捣鼓它,却碰壁了。唯一有意义的是JSON。parse不能正常工作,这是有道理的,因为Chrome已知处理JSON。用不同的方式解析……但我知道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);
}
任何想法?
有人告诉我,如果没有额外的库,就不支持JSON,请参阅这里接受的答案。我也试过这个
try {
clientList = JSON.parse(responseText);
} catch (e) {
alert(e.message);
}
我得到的消息是"JSON是未定义的"。所以答案似乎是正确的。
在进行了更多的故障排除后,发现这是一个跨域的XHR问题。它在Chrome中工作,因为默认情况下,Chrome允许所有域的脚本。我调整了标题,这样Chrome就知道只允许适当的域,但Firefox不允许跨域的XHR。这是通过简单地切换到GM_xmlhttpRequest来解决的,它允许在Firefox中跨域,谢天谢地,Chrome也支持。
谢谢大家的帮助!