laravel5.8使用ajax+验证器验证实现ajax返回验证数据

浏览942

一、创建路由

<?php
Route::prefix("admin")->name("admin.")->group(function (){
     Route::group(['prefix'=>'article'],function(){
         Route::match(["get","post"],"/article_add","Admin\ArticleController@article_add")->name("article.article_add");
    });
});

?>


二、创建验证器:

php artisan make:request CheckArticle

添加如下代码:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;  //注意引入
use Illuminate\Http\Exceptions\HttpResponseException;//注意引入

class CheckArticle extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'sometimes|required|max:60',
            'thumb' => 'sometimes|required',
        ];
    }
    /**
     * 获取已定义验证规则的错误消息。
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required' => '标题不能为空',
            'title.max' => '标题长度不能超过60个字',
            'thumb.required' => '缩略图不能为空',
        ];
    }
//    ajax返回
    public function failedValidation(Validator $validator)
    {
        throw (new HttpResponseException(response()->json([
            'code' => 500,
            'msg' => $validator->errors()->first(),
        ], 200)));
    }
}


三、创建控制器

php artisan make:controller \Admin\ArticleController


<?php
   /*
        * 文章添加
     * */
    public function article_add(CheckArticle $request){
        if($request->isMethod('POST')){
            $data=$request->except('_token');
            $data['created_at']=date('Y-m-d H:i:s');
            $data['updated_at']=date('Y-m-d H:i:s');

            $res=DB::table('article')->insert($data);
            if($res==true){
                return response()->json(['code'=>200,'msg'=>'添加成功','url'=>route('admin.article.article')]);
            }else{
                return response()->json(['code'=>500,'msg'=>'添加失败']);
            }
        }
        return view('admin.article.article_add');
    }
?>


前端:

<meta name="csrf-token" content="{{ csrf_token() }}">

<form role="form" method="post" id="myForm">
	<div class="form-group">
		<label>标题</label>
		<input type="text" name="title" placeholder="标题" class="form-control" style="width: 40%;" required aria-required="true">
	</div>
	<div class="form-group">
		<label>缩略图</label>
		<div id="uploader-demo">
			<div id="fileList" class="uploader-list"></div>
			<div id="filePicker">选择图片</div>
		</div>
		<div id="show_img" style="display:none;">
			<img id="thumb_img" src="" alt="图片" height="100px" width="100px">
		</div>
		<input type="hidden" id="thumb" name="thumb">
	</div>
	<div class="form-group">
		<label>状态</label>
		<div class="radio radio-info radio-inline">
			<input type="radio" id="inlineRadio1" value="0" name="status" checked>
			<label for="inlineRadio1"> 显示 </label>
		</div>
		<div class="radio radio-info radio-inline">
				<input type="radio" id="inlineRadio2" value="1" name="status">
			<label for="inlineRadio2"> 隐藏 </label>
		</div>
	</div>
	<div class="form-group">
		<label>内容</label>
		<script id="content" type="text/plain" style="width:100%;height:500px;" name="content"></script>
	</div>
	<div>
		<button class="btn btn-sm btn-primary pull-left m-t-n-xs" type="button" onclick="save()"><strong>添加</strong>
		</button>
	</div>
</form>

js ajax代码

<script>
    function save() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        // 获取页面已有的一个form表单
        var form = document.getElementById("myForm");
        // 用表单来初始化
        var formData = new FormData(form);

        $.ajax({

            url:"{{route('admin.article.article_add')}}",
            type:'post',
            data:formData,
            timeout:0,
            datatype:'text',
            processData: false,
            contentType: false,
            success:function(msg){
                console.log(msg)
                if(msg.code==200){
                    layer.msg(msg.msg,{icon:1,time:3000}, function() {
                        window.location.href=msg.url
                    });

                }else{
                    layer.msg(msg.msg, { icon:2});
                }
            },error:function () {
                layer.msg('网络错误', { icon:2});
            }
        });

    }
</script>



  • 暂无任何回答