jQuery .getJSON Firefox 3语法错误未定义

时间:2021-07-22 22:41:46

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.

运行这段代码时,我在Firefox 3中会遇到语法错误(未定义的第1行test.js)。警报工作正常(它显示“work”),但我不知道为什么会收到语法错误。

jQuery code:

jQuery代码:

$.getJSON("json/test.js", function(data) {
    alert(data[0].test);
});

test.js:

. 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):

什么好主意吗?我正在为一个更大的.js文件做这方面的工作,但我已经把范围缩小到这段代码。疯狂的是,如果我用一个远程路径替换本地文件,就没有语法错误(这里有一个例子):

http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?

http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?

11 个解决方案

#1


23  

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...

现在的解释是:在firefox 3中(我只支持firefox 3),具有mime类型的“文本/xml”的每个文件都被解析和语法检查。如果您的JSON以“[”开头,则会引发语法错误,如果以“{”开头,则是“格式错误”(我的翻译是“nicht wohlgeformt”)。如果我从本地脚本访问我的json文件——在这个过程中不包含任何服务器——我必须重写mime类型…也许你把那个文件的mime类型设置错了……

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

编辑:在jquery 1.5.1或更高版本中,您可以使用mimeType选项来实现相同的效果。要将其设置为所有请求的默认值,请使用。

$.ajaxSetup({ mimeType: "text/plain" });

You can also use it with $.ajax directly, i.e., your calls translates to

您也可以使用它与$。ajax直接。,你的电话

$.ajax({
    url: "json/test.js",
    dataType: "json",
    mimeType: "textPlain",
    success: function(data){
        alert(data[0].test);
    } });

#2


2  

getJSON may be insisting on at least one name:value pair.
A straight array ["item0","item1","Item2"] is valid JSON, but there's nothing to reference it with in the callback function for getJSON.

getJSON可能坚持使用至少一个名称:值对。一个直接的数组["item0","item1","Item2"]是有效的JSON,但是在getJSON的回调函数中没有什么可引用的。

In this little array of Zip codes:

在这个邮政编码的小数组中:

{"result":[["43001","ALEXANDRIA"],["43002","AMLIN"],["43003","ASHLEY"],["43004","BLACKLICK"],["43005","BLADENSBURG"],["43006","BRINKHAVEN"]]}

... I was stuck until I added the {"result": tag. Afterward I could reference it:

…我被困住了,直到我添加了{“结果”:标签。之后我可以参考:

<script>
       $.getJSON("temp_test_json.php","",
        function(data) {
            $.each(data.result, function(i, item) {
                alert(item[0]+ " " + i);
                if (i > 4 ) return false;
              });
        });
</script>

... I also found it was just easier to use $.each().

…我还发现使用$.each()更容易。

#3


1  

This may sound really really dumb, but change the file extension for test.js from .js to .txt. I had the same thing happen with perfectly valid JSON data files with pretty well any extension except .txt (example: .json, .i18n). Since I've changed the extension, I get the data and use it just fine.

这听起来可能真的很傻,但是更改文件扩展名进行测试。从。js到。txt。对于完全有效的JSON数据文件,除了.txt(示例:. JSON, .i18n)之外,其他扩展都很好。由于我已经更改了扩展名,所以我得到了数据并使用它。

Like I said, it may sound dumb but it worked for me.

就像我说的,这听起来可能很傻,但对我来说确实有用。

#4


1  

HI

I have this same error when testing the web page on my local PC, but once it is up on the hosting server the error no longer happens. Sorry - I have no idea of the reason, but thought it may help someone else track down the reason

当我在本地PC上测试web页面时,我也有同样的错误,但是当它在托管服务器上时,错误就不会再发生了。对不起——我不知道原因,但我想这可能会帮助别人找到原因

#5


0  

Try renaming "test.js" to "test.json", which is what Wikipedia says is the official extension for JSON files. Maybe it's being processed as Javascript at some point.

尝试重命名”测试。js”到“测试。这就是*所说的json文件的官方扩展。可能它在某个时候被作为Javascript处理。

#6


0  

Have you tried disabling all the Firefox extensions?

你试过禁用所有Firefox扩展吗?

I usually get some errors in the Firebug console that are caused by the extensions, not by the webs being visited.

我通常会在Firebug控制台得到一些错误,这些错误是由扩展引起的,而不是通过访问的web。

#7


0  

Check if there's ; at the end of the test.js. jQuery executes eval("(" + data + ")") and semicolon would prevent Firefox from finding closing parenthesis. And there might be some other unseen characters that prevents it from doing so.

检查是否有;在测试的最后。js。jQuery执行eval(“(“+ data +”)”),分号将阻止Firefox查找结束括号。可能还有其他一些看不见的角色阻止它这样做。

I can tell you why this remote location working though, it's because it's executed in completely different manner. Since it has jsoncallback=? as the part of query parameters, jQuery thinks of it as of JSONP and actually inserts it into the DOM inside <script> tags. Try use "json/test.js?callback=?" as target, it might help too.

我可以告诉你为什么这个远程位置可以工作,因为它以完全不同的方式执行。因为它有jsoncallback = ?jQuery作为查询参数的一部分,将其视为JSONP,并实际将其插入到

#8


0  

What kind of webserver are you running that on? I once had an issue reading a JSON file on IIS because it wasn't defined as a valid MIME type.

您在哪种web服务器上运行它?我曾经在IIS上读取JSON文件时遇到过问题,因为它没有定义为有效的MIME类型。

#9


0  

Try configuring the content type of the .js file. Firefox expects it to be text/plain, apparently. You can do that as Peter Hoffmann does above, or you can set the content type header server side.

尝试配置.js文件的内容类型。显然,Firefox希望它是文本/纯文本。您可以像上面的Peter Hoffmann那样做,也可以设置内容类型头服务器端。

This might mean a server-side configuration change (like apache's mime.types file), or if the json is served from a script, setting the content-type header in the script.

这可能意味着服务器端配置更改(如apache的mime)。类型文件),或者如果json来自脚本,则在脚本中设置content-type头。

Or at least that seems to have made the error go away for me.

或者至少这似乎使我的错误消失了。

#10


0  

I had a similar problem but was looping through a for loop. I think the problem might be that the index is out of bound.

我也遇到过类似的问题,不过是在循环中循环。我认为问题可能是指数超出了界限。

  • Kien

#11


0  

For the people who don't use jQuery, you need to call the overrideMimeType method before sending the request:

对于不使用jQuery的人,在发送请求之前需要调用overrideMimeType方法:

var r = new XMLHttpRequest();
r.open("GET", filepath, true);
r.overrideMimeType("text/plain");

#1


23  

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...

现在的解释是:在firefox 3中(我只支持firefox 3),具有mime类型的“文本/xml”的每个文件都被解析和语法检查。如果您的JSON以“[”开头,则会引发语法错误,如果以“{”开头,则是“格式错误”(我的翻译是“nicht wohlgeformt”)。如果我从本地脚本访问我的json文件——在这个过程中不包含任何服务器——我必须重写mime类型…也许你把那个文件的mime类型设置错了……

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

编辑:在jquery 1.5.1或更高版本中,您可以使用mimeType选项来实现相同的效果。要将其设置为所有请求的默认值,请使用。

$.ajaxSetup({ mimeType: "text/plain" });

You can also use it with $.ajax directly, i.e., your calls translates to

您也可以使用它与$。ajax直接。,你的电话

$.ajax({
    url: "json/test.js",
    dataType: "json",
    mimeType: "textPlain",
    success: function(data){
        alert(data[0].test);
    } });

#2


2  

getJSON may be insisting on at least one name:value pair.
A straight array ["item0","item1","Item2"] is valid JSON, but there's nothing to reference it with in the callback function for getJSON.

getJSON可能坚持使用至少一个名称:值对。一个直接的数组["item0","item1","Item2"]是有效的JSON,但是在getJSON的回调函数中没有什么可引用的。

In this little array of Zip codes:

在这个邮政编码的小数组中:

{"result":[["43001","ALEXANDRIA"],["43002","AMLIN"],["43003","ASHLEY"],["43004","BLACKLICK"],["43005","BLADENSBURG"],["43006","BRINKHAVEN"]]}

... I was stuck until I added the {"result": tag. Afterward I could reference it:

…我被困住了,直到我添加了{“结果”:标签。之后我可以参考:

<script>
       $.getJSON("temp_test_json.php","",
        function(data) {
            $.each(data.result, function(i, item) {
                alert(item[0]+ " " + i);
                if (i > 4 ) return false;
              });
        });
</script>

... I also found it was just easier to use $.each().

…我还发现使用$.each()更容易。

#3


1  

This may sound really really dumb, but change the file extension for test.js from .js to .txt. I had the same thing happen with perfectly valid JSON data files with pretty well any extension except .txt (example: .json, .i18n). Since I've changed the extension, I get the data and use it just fine.

这听起来可能真的很傻,但是更改文件扩展名进行测试。从。js到。txt。对于完全有效的JSON数据文件,除了.txt(示例:. JSON, .i18n)之外,其他扩展都很好。由于我已经更改了扩展名,所以我得到了数据并使用它。

Like I said, it may sound dumb but it worked for me.

就像我说的,这听起来可能很傻,但对我来说确实有用。

#4


1  

HI

I have this same error when testing the web page on my local PC, but once it is up on the hosting server the error no longer happens. Sorry - I have no idea of the reason, but thought it may help someone else track down the reason

当我在本地PC上测试web页面时,我也有同样的错误,但是当它在托管服务器上时,错误就不会再发生了。对不起——我不知道原因,但我想这可能会帮助别人找到原因

#5


0  

Try renaming "test.js" to "test.json", which is what Wikipedia says is the official extension for JSON files. Maybe it's being processed as Javascript at some point.

尝试重命名”测试。js”到“测试。这就是*所说的json文件的官方扩展。可能它在某个时候被作为Javascript处理。

#6


0  

Have you tried disabling all the Firefox extensions?

你试过禁用所有Firefox扩展吗?

I usually get some errors in the Firebug console that are caused by the extensions, not by the webs being visited.

我通常会在Firebug控制台得到一些错误,这些错误是由扩展引起的,而不是通过访问的web。

#7


0  

Check if there's ; at the end of the test.js. jQuery executes eval("(" + data + ")") and semicolon would prevent Firefox from finding closing parenthesis. And there might be some other unseen characters that prevents it from doing so.

检查是否有;在测试的最后。js。jQuery执行eval(“(“+ data +”)”),分号将阻止Firefox查找结束括号。可能还有其他一些看不见的角色阻止它这样做。

I can tell you why this remote location working though, it's because it's executed in completely different manner. Since it has jsoncallback=? as the part of query parameters, jQuery thinks of it as of JSONP and actually inserts it into the DOM inside <script> tags. Try use "json/test.js?callback=?" as target, it might help too.

我可以告诉你为什么这个远程位置可以工作,因为它以完全不同的方式执行。因为它有jsoncallback = ?jQuery作为查询参数的一部分,将其视为JSONP,并实际将其插入到

#8


0  

What kind of webserver are you running that on? I once had an issue reading a JSON file on IIS because it wasn't defined as a valid MIME type.

您在哪种web服务器上运行它?我曾经在IIS上读取JSON文件时遇到过问题,因为它没有定义为有效的MIME类型。

#9


0  

Try configuring the content type of the .js file. Firefox expects it to be text/plain, apparently. You can do that as Peter Hoffmann does above, or you can set the content type header server side.

尝试配置.js文件的内容类型。显然,Firefox希望它是文本/纯文本。您可以像上面的Peter Hoffmann那样做,也可以设置内容类型头服务器端。

This might mean a server-side configuration change (like apache's mime.types file), or if the json is served from a script, setting the content-type header in the script.

这可能意味着服务器端配置更改(如apache的mime)。类型文件),或者如果json来自脚本,则在脚本中设置content-type头。

Or at least that seems to have made the error go away for me.

或者至少这似乎使我的错误消失了。

#10


0  

I had a similar problem but was looping through a for loop. I think the problem might be that the index is out of bound.

我也遇到过类似的问题,不过是在循环中循环。我认为问题可能是指数超出了界限。

  • Kien

#11


0  

For the people who don't use jQuery, you need to call the overrideMimeType method before sending the request:

对于不使用jQuery的人,在发送请求之前需要调用overrideMimeType方法:

var r = new XMLHttpRequest();
r.open("GET", filepath, true);
r.overrideMimeType("text/plain");