javascript - 使用 laravel 验证后,ajax 上的成功函数

标签 javascript jquery ajax laravel

我通过ajax使用laravel对表单进行了验证。发送数据和验证工作正常,但是当收到js代码中的答案时,success函数永远不会被执行;如果验证中出现错误,则执行错误函数;如果验证中没有错误,则也会输入错误。 出错时,它返回 laravel 状态:422,如果没有错误,则返回 laravel 状态:200。

感谢您能够提供的帮助:)

js:

function send(event){

    event.preventDefault();

    $.ajax({


        type: 'post',
        url: userAjax,
        dataType: 'json',
        data: {
            name: $('#name').val(),
            email: $('#email').val(),
            password: $('#password').val(),
            cpassword: $('#cpassword').val(),
            _token: $('#new-user').attr('data-token')
        },
        beforeSend: function()
        {
            $("#nameError").fadeOut();

        },
        success: function(errors){

            $('#Register').modal('hide');

        },
        error: function(errors) {


            console.log(errors);

        }

    });

}

拉拉维尔: 用户 Controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Http\Requests\UserRequest;

class UserController extends Controller
{
    public function index()
    {
        return view('home');
    }
    public function NewUser(UserRequest $request)
    {
        // laravel will validate request itself automatically and
        // will go on if validate pass or will return back with
        // status code 422, input and errors otherwise

        CreateNewUser($request);

    }

    Protected function CreateNewUser(Request $request){

    }


}

用户请求:

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class UserRequest extends Request
{
    /**
     * 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 [
            'name' => 'required|max:255',
//            'email' => 'required|email|max:255|unique:users',
//            'password' => 'required|min:8|same:cpassword',
//            'cpassword'=> 'required|min:8',
        ];
    }

}

最佳答案

这是因为您的代码中有错误。

CreateNewUser($request);

需要

$this->CreateNewUser($request);

还有

Protected function CreateNewUser(Request $request){

需要:

protected function CreateNewUser(Request $request){

关于javascript - 使用 laravel 验证后,ajax 上的成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37778150/

相关文章:

javascript - 通过Modal显示汇总表单

jQuery 可对内容可编辑的项目进行排序

php - 数据表不适用于 ajax 调用

javascript - 了解如何从 AJAX 调用捕获数据

ajax - 成功的 Ajax 请求后关闭 Bootstrap 模态表单

php - 将 PHP 时间转换为 PHP 中的 Javascript 时间

javascript - Angular 4 : Table ng-if value equals row header

javascript - JQuery 下拉菜单在 WordPress WooCommerce 商店页面上不起作用

javascript - React 中的组件相互重叠

jquery - append 的图像不会有悬停效果