SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符-FireBug报告此错误.有什么办法吗? [英] SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data -- FireBug reports this error. Any solution?
问题描述
我已经使用Laravel Response :: json生成JSON响应.
I have used Laravel Response::json to generate a JSON response.
return Response::json(array('subjects' => $subjects, 'year' => $year, 'sem' => $sem));
运行请求时,我得到一个有效的JSON(在JSONLint中进行了测试)作为响应.
When I run the request, I get a valid JSON (tested in JSONLint) as a response.
但是以下jQuery方法失败:$.parseJSON(data)
But the following jQuery method fails: $.parseJSON(data)
我在FireBug中收到以下错误:
I get the following error in FireBug:
SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
我收到的回复:
{
"subjects": [
{
"id": 1,
"name": "Control Systems",
"semester": 1,
"year": 3,
"branch_id": 4
},
{
"id": 2,
"name": "Analog Communications",
"semester": 1,
"year": 3,
"branch_id": 4
},
{
"id": 3,
"name": "Linear IC Applications",
"semester": 1,
"year": 3,
"branch_id": 4
},
{
"id": 4,
"name": "Antennas & Wave Propagation",
"semester": 1,
"year": 3,
"branch_id": 4
}
],
"year": 3,
"sem": 2
}
以及我要解析的代码:
$(document).ready(function() {
$('#branchAndSubjects').click(function() {
$.post('/findBranchAndSubjects', {
roll: roll,
_token: "{{csrf_token()}}"
}, function(data) {
var subjects = $.parseJSON(data);
});
});
});
推荐答案
如果您正在ajax成功处理程序中执行,因为您正在ajax中执行$.parseJSON(data)
$.parseJSON(data)
成功处理程序,问题几乎可以肯定是jQuery已经已经为您解析了它. jQuery将查看响应的Content-Type
,如果响应为application/json
,它将对其进行解析,并将解析的结果提供给成功处理程序.如果将其传递给$.parseJSON
,将会发生的第一件事是它将被转换回字符串(对于您来说是"[object Object]"
),然后$.parseJSON
将无法解析该字符串.
If you're doing the Since you're doing the $.parseJSON(data)
in an ajax success handler$.parseJSON(data)
in an ajax success handler, the problem is almost certainly that jQuery has already parsed it for you. jQuery will look at the Content-Type
of the response and, if it's application/json
, it will parse it, and provide the parsed result to your success handler. The first thing that will happen if you pass that into $.parseJSON
will be that it will get converted back to a string ("[object Object]"
, in your case), which $.parseJSON
will then fail to parse.
只需按原样使用data
,就已经有了对象,这要归功于自动解析:
Just use data
as-is, it's already an object, thanks to the automatic parsing:
$(document).ready(function() {
$('#branchAndSubjects').click(function() {
$.post('/findBranchAndSubjects', {
roll: roll,
_token: "{{csrf_token()}}"
}, function(data) {
console.log(data.year); // 3
console.log(data.subjects.length); // 4
console.log(data.subjects[0].name); // Control Systems
});
});
});
这篇关于SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符-FireBug报告此错误.有什么办法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!