Laravel JSON响应缺失了右方方括号,Ajax抛出了Parseerror

发布于 2025-02-04 06:27:50 字数 890 浏览 3 评论 0原文

查看

$.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".
            }
        })

Company Controller

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}

如您所见,响应缺少结束括号]使JSON无效和Ajax无法解析它。这是Laravel 9.15中的错误还是我做错了什么?

View

$.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".
            }
        })

CompanyController

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.
}

Response

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

As you can see, response is missing ending bracket ] making json invalid and ajax fails to parse it. Is it a bug in Laravel 9.15 or am I doing something wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是你 2025-02-11 06:27:50

他们是错误的语法。尝试以下操作: -

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

They are wrong syntax.. Try this:-

public function ajaxGetClients($id)
{
    return response()->json(Company::findOrFail($id)->clients->toArray()); // versions without toArray() or with toJson() also does not work.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文