php - SyntaxError : JSON. parse : unexpected character at line 1 column 2 of the JSON data -- FireBug reports this error. 任何解决方案?

标签 php jquery json

<分区>

我已使用 Laravel Response::json 生成 JSON 响应。

return Response::json(array('subjects' => $subjects, 'year' => $year, 'sem' => $sem));

当我运行请求时,我得到一个有效的 JSON(在 JSONLint 中测试)作为响应。

但是下面的 jQuery 方法失败了:$.parseJSON(data)

我在 FireBug 中收到以下错误:

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 成功处理程序中执行 $.parseJSON(data) 因为您正在执行 $.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
        });
    });
});

关于php - SyntaxError : JSON. parse : unexpected character at line 1 column 2 of the JSON data -- FireBug reports this error. 任何解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29741378/

相关文章:

php - Ajax 多下拉返回值- php mysql

json - 如何使用 Enum 类型的字段执行 Typesafe JSON?

javascript - 通过 PHP 将 mySQL 数据拉入 Javascript 对象数组

php - 如何通过php输出除号

javascript - Chrome 中带有文本框的 sweetalert 对话框

javascript - 如何使用 "this"关键字而不是元素 ID?

php - 将来自 JSON 的数据放入 MySQL 数据库

json - 如何将具有动态字段的 JSON 对象映射到 Go 结构

php - 带有 OR 和 AND 的 SELECT 语句在数据库未完全填充时成功,在完全填充时失败。

php - 格式化MySql时间显示给客户端,undefined offset错误