编程语言
首页 > 编程语言> > php – 如何在laravel中使用ajax验证输入数据

php – 如何在laravel中使用ajax验证输入数据

作者:互联网

PostsController类里面的testAjax函数:

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(不可处理的实体)错误.为什么我的方法在这里是错误的,如何打印错误消息呢.请帮忙.先感谢您.
enter image description here
enter image description here

解决方法:

您的方法实际上没有错,只需要在您的ajax请求中捕获错误响应,因为当Laravel验证失败时,它会抛出错误422(不可处理的实体)以及相应的错误消息.

/**Ajax code**/
$.ajax({
    type: "post",
    url:"{{URL::to('/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"
    ]);

  }

标签:laravel-5-6,laravel-validation,php,laravel,ajax
来源: https://codeday.me/bug/20190727/1550100.html