laravel使用ajax 表单提交后台验证如何返回错误信息???

2022-09-11 12:43:52 浏览数 (1)

下面以添加角色为例加以说明

代码语言:javascript复制
#后台处理
 /**
     * 添加处理
     *
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function store(Request $request)
    {
        //
        $validator = Validator::make($request->all(), [
            'name' => 'required|unique:roles,name'
        ], [
            'name.required' => '角色名称不能为空',
            'name.unique' => '角色名称不能重复'
        ]);
        if ($validator->fails()) {
            return ['status' => 9000, 'msg' => $validator->errors()->first()];
        }
        Role::create($request->only('name'));
        return ['status' => 0, 'msg' => '添加角色成功'];
    }
#前台处理
$('#form-role-add').validate({
        rules: {
            name: {
                required: true
            }
        },
        messages: {
            name: {
                required: "角色名称不能为空",
            }
        },
        onKeyup:false,
        success:"valid",
        //验证通过后处理
        submitHandler:function (form) {
            let url = $(form).attr('action');
            let data = $(form).serialize();
            $.post(url, data).then(ret => {
                 if(ret.status== 0) {
                   layer.msg(ret.msg,{icon:1,time:2000}, ()=> {
                       location.href = "{{route('admin.role.index')}}";
                   });
                } else {
                     layer.msg(ret.msg,{icon:2,time:2000});
                 }
            });
        }
    });

0 人点赞