我使用Laravel Response :: json生成JSON响应.
return Response::json(array('subjects' => $subjects, 'year' => $year, 'sem' => $sem));
Run Code Online (Sandbox Code Playgroud)
当我运行请求时,我得到一个有效的JSON(在JSONLint中测试)作为响应.
但是以下jQuery方法失败了: $.parseJSON(data)
我在FireBug中收到以下错误:
SyntaxError:JSON.parse:JSON数据的第1行第2列的意外字符
我收到的回复:
{
"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
}
Run Code Online (Sandbox Code Playgroud)
和我试图解析它的代码:
$(document).ready(function() {
$('#branchAndSubjects').click(function() {
$.post('/findBranchAndSubjects', {
roll: roll,
_token: "{{csrf_token()}}"
}, function(data) {
var subjects = $.parseJSON(data);
});
});
});
Run Code Online (Sandbox Code Playgroud)
T.J*_*der 21
如果你因为你正在$.parseJSON(data)
在ajax成功处理程序中进行操作$.parseJSON(data)
使用ajax成功处理程序,问题几乎肯定是jQuery 已经为你解析了它.jQuery将查看Content-Type
响应,如果是application/json
,它将解析它,并将解析后的结果提供给您的成功处理程序.如果你传入它将会发生的第一件事是它将$.parseJSON
被转换回一个字符串("[object Object]"
在你的情况下),然后$.parseJSON
将无法解析.
data
由于自动解析,只需按原样使用,它已经是一个对象:
$(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
});
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24426 次 |
最近记录: |