通过$ .ajax请求JSON文件时的怪异JSON行为 [英] Weird JSON behavior when requesting a json file via $.ajax
问题描述
我有一个json文件(text2.json)和一个文本文件(text2.txt),其内容与text2.json完全相同.
I have a json file (text2.json) and a text file (text2.txt) which has the exact same content as text2.json.
通过$ .ajax请求json文件时,我发现它很有趣:
I found it quite interesting when requesting json file via $.ajax:
向Web服务器请求text2.json:
Requesting text2.json to web server:
$.ajax({
url: "./scripts/text2.json",
dataType:"json",
success: function(data){
alert('success');
},
error: function(){alert('error');}
});
这将提示错误.
向Web服务器请求text2.txt:
Requesting text2.txt to web server:
$.ajax({
url: "./scripts/text2.txt",
dataType:"json",
success: function(data){
alert('success');
},
error: function(){alert('error');}
});
这会提醒成功.
到目前为止,我只有2天的javascript经验,我只是想知道是什么导致这种折衷...
As of now, I only have 2-day javascript experience and I was just wondering what causes this trade-off...
编辑
对于text2.json +类型:"json",我错误地修改了我的alert():就像你们建议的那样.然后警报发出"[object object]",因为我的json文件是"{"result":true,"count":2}.这看起来像是一个空对象或其他东西.
For text2.json + type:"json", I revised my alert() in error: as you guys suggested. Then the alert gives "[object object]" as my json file is "{"result":true, "count":2}".That just looks like an empty object or something.
然后我在将text2.json请求为json数据类型时检测到"parseerror".我不确定此信息.看起来有些初始设置不正确.有人想给我一个提示吗?
Then I detected there's a "parseerror" when requesing text2.json as json dataType. I am not sure about this info. Looks like some initial settings is incorrect. Anyone wanna give me a hint?
看起来像我的json文件非常像格式错误的json.可能就是这种情况...
Looks like my json file is so much like a malformed json. That might be the case ...
推荐答案
该错误可能与响应的标头有关.您正在指定json数据类型,因此预期的标头应为application/json
Probably the error is related to the headers of the response. You are specifying a json datatype, thus the expected headers should be of type application/json
这篇关于通过$ .ajax请求JSON文件时的怪异JSON行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!