jQuery .getJSON Firefox 3语法错误未定义 [英] jQuery .getJSON Firefox 3 Syntax Error Undefined
问题描述
jQuery代码:
$。getJSON(json / test.js,function(data){
alert(data [0] .test);
});
test.js:
[{test:work}]
我正在处理这个更大的.js文件,但我已经缩小到这个代码。真正疯狂的是,如果我用远程路径替换本地文件,则没有语法错误(这里是一个例子):
$ .ajaxSetup({'beforeSend':function(xhr){
if(xhr.overrideMimeType)
xhr.overrideMimeType(text / plain);
}
}) ;
现在解释:
在firefox 3(和我asume只有firefox三)具有MIME类型的text / xml被解析和语法检查。如果你用一个[开始你的JSON,将会引发一个语法错误,如果它以{开头,这是一个格式错误(我的翻译为nicht wohlgeformt)。
如果我从本地脚本访问我的json文件 - 这个进程中没有包含服务器 - 我必须重写MIME类型...也许你设置你的MIME类型为非常错误的文件...
如何添加这一小段代码可以节省您的错误信息
编辑:在jQuery 1.5.1或更高版本中,您可以使用mimeType选项来实现相同的效果。要将其设置为所有请求的默认值,请使用
$。ajaxSetup({mimeType:text / plain});
您也可以直接使用$ .ajax,即您的调用转换为
$ b $
$。ajax({
url:json / test.js,
dataType:json,
mimeType:textPlain,
success:function(data){
alert(data [0] .test);
}});
I'm getting a syntax error (undefined line 1 test.js) in Firefox 3 when I run this code. The alert works properly (it displays 'work') but I have no idea why I am receiving the syntax error.
jQuery code:
$.getJSON("json/test.js", function(data) {
alert(data[0].test);
});
test.js:
[{"test": "work"}]
Any ideas? I'm working on this for a larger .js file but I've narrowed it down to this code. What's crazy is if I replace the local file with a remote path there is no syntax error (here's an example):
I found a solution to kick that error
$.ajaxSetup({'beforeSend': function(xhr){
if (xhr.overrideMimeType)
xhr.overrideMimeType("text/plain");
}
});
Now the explanation: In firefox 3 (and I asume only firefox THREE) every file that has the mime-type of "text/xml" is parsed and syntax-checked. If you start your JSON with an "[" it will raise an Syntax Error, if it starts with "{" it's an "Malformed Error" (my translation for "nicht wohlgeformt"). If I access my json-file from an local script - no server is included in this progress - I have to override the mime-type... Maybe you set your MIME-Type for that very file wrong...
How ever, adding this little piece of code will save you from an error-message
Edit: In jquery 1.5.1 or higher, you can use the mimeType option to achieve the same effect. To set it as a default for all requests, use
$.ajaxSetup({ mimeType: "text/plain" });
You can also use it with $.ajax directly, i.e., your calls translates to
$.ajax({
url: "json/test.js",
dataType: "json",
mimeType: "textPlain",
success: function(data){
alert(data[0].test);
} });
这篇关于jQuery .getJSON Firefox 3语法错误未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!