如何显示JSON HTTP 422响应用户使用jQuery Ajax时?用户、HTTP、JSON、Ajax

2023-09-10 20:23:19 作者:思念成灾。

您好我有这个奇怪的问题,我的JSON,我试图返回我的网页上的错误信息和显示,我已经尝试洙许多解决方案我已经在网上找到,但我不断收到任何未定义或空或什么都取决于我怎么努力,这是我的javascript:

  $。阿贾克斯({
                键入:POST,
                网址:/认证/注册,
                标题:{
                    X-XSRF令牌'。$(元[名称='csrf_token'])ATTR(内容)
                },
                数据: {
                    电子邮件:$ scope.d.email,
                    密码:$ scope.d.password,
                    password_confirmation:$ scope.d.password_confirmation
                },
                数据类型:JSON,
                成功:功能(数据){
                    //
                },
                错误:功能(数据){
                    $ scope.d.errors = data.responseJSON;
                    警报($ scope.d.errors);

                }
            });
 

这是返回什么:

  {名:名字的字段是必需的]}
 
JQuery JSON支持

解决方案

如果您在返回 422 ,然后jQuery将调用您的故障/错误回调。一个错误的签名/失败回调是:

函数(jqXHR jqXHR,字符串textStatus,字符串errorThrown)

在错误的情况下,jQuery的不分析你的反应,你需要自己手动操作,如果你想获得它,使你的错误回调是这样的:

 函数(XHR,状态,ERR){
    VAR responseJSON = JSON.parse(xhr.responseText);
    $ scope.d.errors = responseJSON;
    警报($ scope.d.errors);
    //做的东西与你的错误信息presumably ...
}
 

Hello i am having this weird issue with my json, i am trying to return error messages and display on my page, i have tried soo many solutions i have found online but i keep getting either 'undefined' or 'null' or nothing at all depending on what i try, this is my javascript:

           $.ajax({
                type: "POST",
                url: "/auth/register",
                headers : {
                    'X-XSRF-Token': $("meta[name='csrf_token']").attr("content")
                },
                data: {
                    email: $scope.d.email,
                    password: $scope.d.password,
                    password_confirmation: $scope.d.password_confirmation
                },
                dataType: 'json',
                success: function(data) {
                    //
                },
                error: function(data) {
                    $scope.d.errors = data.responseJSON;
                    alert($scope.d.errors);

                }
            });

this is what is returned:

{"name":["The name field is required."]}

解决方案

If you are returning a 422, then jQuery will invoke your fail/error callback. The signature for an error/fail callback is:

Function( jqXHR jqXHR, String textStatus, String errorThrown )

In the case of the error jQuery does not parse the response for you, you need to manually do it yourself if you want access to it, making your error callback look like:

function(xhr, status, err) {
    var responseJSON = JSON.parse(xhr.responseText);
    $scope.d.errors = responseJSON;
    alert($scope.d.errors);
    // do stuff with your error messages presumably...
}

 
精彩推荐