【问题标题】:How to validate input data using ajax in laravel如何在 laravel 中使用 ajax 验证输入数据
【发布时间】:2018-08-26 06:58:52
【问题描述】:

testAjax 函数 内部 PostsController 类

public function testAjax(Request $request)
  {
    $name = $request->input('name');
    $validator = Validator::make($request->all(), ['name' => 'required']);

    if ($validator->fails()){
        $errors = $validator->errors();
        echo $errors;
    }
    else{
      echo "welcome ". $name;
    }

  }

web.php 文件中:

Route::get('/home' , function(){
  return view('ajaxForm');
});

Route::post('/verifydata', 'PostsController@testAjax');

ajaxForm.blade.php:

<script src="{{ asset('public/js/jquery.js') }}"></script>

  <input type="hidden" id="token" value="{{ csrf_token() }}">
  Name<input type="text" name="name" id="name">
  <input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
  $(document).ready(function(){
      $("#submit").click(function(){
        var name = $("#name").val();
        var token = $("#token").val();
        /**Ajax code**/
        $.ajax({
        type: "post",
        url:"{{URL::to('/verifydata')}}",
        data:{name:name,  _token: token},
        success:function(data){
                //console.log(data);
                $('#success_message').fadeIn().html(data);
            }
          });
          /**Ajax code ends**/    
      });
  });
</script>

因此,当通过输入一些数据单击提交按钮时,输出消息(echo "welcome ".$name;) 正在打印。但是,当我单击带有空文本框的提交按钮时,它不会从控制器打印错误消息,并且会在控制台中引发 422(不可处理实体)错误。为什么我的方法在这里是错误的,然后我该如何打印错误消息。请帮忙。先感谢您。

【问题讨论】:

  • 从 laravel 发送 json 数据并从 ajax 响应中读取
  • Laravel 已经发送了一个很好的错误响应,你需要做的就是在客户端处理错误
  • 我建议你使用 axios 和 Vue.js 来做。很容易。您可以将数据发送到 laravel,然后在控制器中创建 if(request()-&gt;wantsJson()) 并返回数据。然后在前端,你抓住它。并显示在屏幕上。这可能看起来很难,但实际上是 1 分钟的工作。

标签: php ajax laravel laravel-validation laravel-5.6


【解决方案1】:

您的方法实际上并没有错,只是您需要在 ajax 请求上捕获错误响应。然而,当 Laravel 验证失败时,它会抛出一个 Error 422 (Unprocessable Entity) 以及相应的错误消息。

/**Ajax code**/
$.ajax({
    type: "post",
    url: "{{ url('/verifydata') }}",
    data: {name: name,  _token: token},
    dataType: 'json',              // let's set the expected response format
    success: function(data){
         //console.log(data);
         $('#success_message').fadeIn().html(data.message);
    },
    error: function (err) {
        if (err.status == 422) { // when status code is 422, it's a validation issue
            console.log(err.responseJSON);
            $('#success_message').fadeIn().html(err.responseJSON.message);
            
            // you can loop through the errors object and show it to the user
            console.warn(err.responseJSON.errors);
            // display errors on each form field
            $.each(err.responseJSON.errors, function (i, error) {
                var el = $(document).find('[name="'+i+'"]');
                el.after($('<span style="color: red;">'+error[0]+'</span>'));
            });
        }
    }
});
/**Ajax code ends**/   

在你的控制器上

public function testAjax(Request $request)
{
    // this will automatically return a 422 error response when request is invalid
    $this->validate($request, ['name' => 'required']);

    // below is executed when request is valid
    $name = $request->name;

    return response()->json([
         'message' => "Welcome $name"
    ]);

  }

【讨论】:

  • 这很棒。我唯一不喜欢的是,当错误仍然存​​在并且用户再次按下提交按钮时,错误会多次显示。
【解决方案2】:

这是一种更好的验证方法:

在您的控制器中:

public function testAjax(Request $request)
{
   $this->validate($request, [ 'name' => 'required' ]);
   return response("welcome ". $request->input('name'));
}

然后框架将为您创建一个验证器并验证请求。如果验证失败,它将抛出 ValidationException

假设您没有覆盖验证异常的呈现方式,默认代码 the built-in exception handler 将运行

protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
        if ($e->response) {
            return $e->response;
        }
        $errors = $e->validator->errors()->getMessages();
        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }
        return redirect()->back()->withInput($request->input())->withErrors($errors);
}

这再次由框架为您处理。

在客户端你应该能够做到:

<script>
  $(document).ready(function(){
      $("#submit").click(function(){
        var name = $("#name").val();
        var token = $("#token").val();
        /**Ajax code**/
        $.ajax({
           type: "post",
           url:"{{URL::to('/verifydata')}}",
           data:{name:name,  _token: token},
           success:function(data){
              //console.log(data);
              $('#success_message').fadeIn().html(data);
           },
           error: function (xhr) {
               if (xhr.status == 422) {
                   var errors = JSON.parse(xhr.responseText);
                   if (errors.name) {
                       alert('Name is required'); // and so on
                   }
               }
           }
        });
          /**Ajax code ends**/    
      });
  });
</script>

【讨论】:

    【解决方案3】:

    在 php 控制器中处理的最佳方式:

            $validator = \Validator::make($request->all(), [
            'footballername' => 'required',
            'club' => 'required',
            'country' => 'required',
        ]);
        
        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }
        return response()->json(['success'=>'Record is successfully added']);
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 2016-10-12
      • 2017-02-04
      • 2016-12-16
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      相关资源
      最近更新 更多