简体   繁体   English

如何使用Jquery ajax从Laravel输出json响应(发生错误时)

[英]How to output the json response from Laravel using Jquery ajax (when errors occur)

I have no problem with the request and response process, Until I try to parse/process the json data returned from laravel when the error occurs. 我在请求和响应过程中没有问题,直到我尝试解析/处理发生错误时从laravel返回的json数据。

I want to display a messsage error when the uploaded file is larger than the system accepts. 当上传的文件大于系统接受的大小时,我想显示一条消息错误。 My action is something like this: 我的动作是这样的:

...
if($_FILES['file1']['size'] > 0)
  {
    http_response_code(413);
    return Response()->json(["errorMsg" => "Your file is too large!"], 413);


  }
....

Client code: 客户代码:

  $.ajax({
                type: "POST",
                url: "/anuncio/realizar_upload_foto",
                 contentType: false,
                cache: false,
                dataType: "JSON",
               processData: false

...

...
    error: function (xh, jso) 

            {


                  alert(jso.errorMsg); //undefined here



                }

            });

In your way, you should find your data in xh.responseJSON.errorMsg 用您的方式,您应该在xh.responseJSON.errorMsg找到您的数据

But you should follow REST Api practice. 但是您应该遵循REST Api的做法。

First of all you should return json code 200 and pass your status message like. 首先,您应该返回json代码200并传递您的状态消息。

return response()->json([
    "status" => "success",
    "data" => [....yourdata]
], 200);

in error case 在错误的情况下

return response()->json([
    "status" => "error",
    "msg" => "Your file is too large!"
], 4**);

According to the jQuery.ajax() document , the error callback accepts 3 parameters: 根据jQuery.ajax()文档error回调接受3个参数:

error 错误

Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) 类型:函数(jqXHR jqXHR,字符串textStatus,字符串errorThrown)

The second parameter ( jso in your code) is just a String indicating status ( "error" for example). 第二个参数(代码中的jso )只是一个指示状态的字符串(例如"error" )。 It does not contain any HTTP response body data. 它不包含任何HTTP响应正文数据。

To get errorMsg in the error callback, you need to use the first parameter ( jqXHR ). 要在error回调中获取errorMsg ,您需要使用第一个参数( jqXHR )。 Example code would be: 示例代码为:

error: function(jqXHR, status, error) {
  var errorObj = jqXHR.responseJSON; // This only works when dataType is defined as "JSON", or the "Content-Type" of HTTP response is "application/json". Otherwise, use the below general code.
  //var errorObj = JSON.parse(jqXHR.responseText);

  alert(errorObj.errorMsg);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM