Laravel-json响应缺少右方括号,ajax抛出parseerror



查看

$.ajax({
type: 'GET',
url: '/company/ajaxGetClients/1',
dataType: 'json',
success: function(response) {
console.log(response); // Expecting this response logged in console.
},
error: function (a, e){
console.log(e); // This logs "parseerror".
}
})

公司控制员

public function ajaxGetClients($id)
{
return response(Company::findOrFail($id)->clients->toArray()); // versions without toArray() or with toJson() also does not work. response()->json() same result.
}

响应

[{"id":1,"name":"John","company_id":1,"phone":null,"email":null,"created_at":null,"updated_at":null}

正如您所看到的,response缺少结束括号],导致json无效,ajax无法解析它。这是Laravel 9.15中的错误还是我做错了什么?

它们是错误的语法。。试试这个:-

public function ajaxGetClients($id)
{
return response()->json(Company::findOrFail($id)->clients->toArray()); // versions without toArray() or with toJson() also does not work.
}

最新更新