【问题标题】:Laravel 5.2 HTML is returned instead of JSON返回 Laravel 5.2 HTML 而不是 JSON
【发布时间】:2017-08-02 07:10:54
【问题描述】:

我在使用 ajax 时遇到问题。我想检索某个表的所有记录,所以我有这个 ajax 调用:

$('#chooseInvBtn').on('click', function(){
            $.ajax({
                type: "POST",
                url : "admin/officer_data",
                data: { _token: $('#csrf-token').val() },
                dataType : "json",
                success : function(data){
                    if(Object.keys(data).length > 0) {


                    }
                },
                error : function(xhr, status){
                    console.log(xhr);
                    console.log(status);
                }
            });
        });

有了这个,我得到 200 ok parseerror。但是当我将 json 数据类型更改为 html 数据类型时,它不再返回任何错误。不幸的是,我需要 json 来检索数据。这就是我的控制器中的内容:

$officers_list = Officer::all();

        //Convert data to array
        $officers = array();

        foreach ($officers_list as $officer)
        {
            $officers['OfficerID'] = $officer->OfficerID;
            $officers['OfficerName'] = $officer->ORank . ' ' . $officer->OFirstName . ' ' . $officer->OMiddleName . ' ' . $officer->OLastName;
            $officers['Photo'] = isset($officer->OPhoto) ? $officer->OPhoto : "";
            $officers['ContactNumber'] = isset($officer->OContactNumber) ? $officer->OContactNumber : "";
        }

        return Response::json($officers);

这也是我使用其他 ajax 调用的方式。但是不知道这次为什么会出错。

【问题讨论】:

    标签: javascript php json ajax laravel


    【解决方案1】:

    删除dataType: "json" 行。

    在 laravel 中,你正在做

    return Response::json($officers); //equivalent to
    return response()->json($officers);//
    

    也就是说,它已经返回了 JSON 格式的数据。所以你实际上不需要再解析它了。

    通常如果你在 Laravel 中这样做,

    return $officers;
    

    这时您需要将 dataType: 'json' 添加到您的 ajax 中。

    简而言之,只需删除 dataType 行。我认为你应该很高兴。

    【讨论】:

    • 我已经尝试过了。我刚刚检查了我的模型,发现文件末尾有一个逗号。我不确定这是否是导致错误的原因,因为我决定不再在此过程中使用 ajax。
    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 2015-08-16
    • 2021-09-25
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多