【问题标题】:Laravel 5.4, AJAX Not Erroring When it ShouldLaravel 5.4,AJAX 应该不会出错
【发布时间】:2017-11-29 03:35:51
【问题描述】:

我一直在尝试关注很多关于如何在 Laravel 中处理 AJAX 请求的不同文章。他们都是不同的..

我有一个最终没有向我抛出 500 错误,但它实际上并没有像您想象的那样抛出验证错误。

我的代码将始终默认为 AJAX 成功部分,而不是错误部分,并在控制台中显示“成功”,但也会显示我的控制器返回的错误 JSON。

我不知道我的伙计们发生了什么事。如果您能帮助我,将不胜感激!

控制器

public function store(Request $request)
    {
        if ($request->ajax())
        {
            $rules = array(
                "name"      => "required|string|unique:brands|max:255",
                "contact"   => "string|max:255",
                "email"     => "string|max:255",
                "phone"     => "max:12"
            );

            $validator = Validator::make(Input::all(), $rules);

            if ($validator->fails())
            {
                return \Response::json(array(
                    "errors" => $validator->getMessageBag()->toArray()
                ));
            }
            else
            {
                // Submit to the database
                $brand = new Brand();

                $brand->name        = $request->name;
                $brand->contact     = $request->contact;
                $brand->email       = $request->email;
                $brand->phone       = $request->phone;
                $brand->created_by  = auth()->user()->id;
                $brand->updated_by  = auth()->user()->id;

                $brand->save();

                return \Response::json($brand);
            }
        }
        else
        {
            return \Response::json(array("error" => "response was not JSON"));
        }
    }

路线

// Brands
Route::get('/brands', 'BrandsController@index')->name('brands');
Route::post('/brands/store', 'BrandsController@store');

AJAX(通过 {{ Html::script() }} 嵌入)

$(document).ready(function() {

    /**
    * Save a new brand to the database via AJAX
    */
    var url = "/brands/store";

    $("#save").click(function (e) {

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content'),
            }
        });

        e.preventDefault();

        var formData = {
            name:       $('#name').val(),
            contact:    $('#contact').val(),
            email:      $('#email').val(),
            phone:      $('#email').val(),
        }

        var type = "POST";

        console.log(formData);

        $.ajax({

            type: type,
            url: url,
            data: formData,
            dataType: 'json',
            success: function (data) {
                console.log(data);
            },
            error: function (data) {
                console.log("Error: ", data);
                console.log("Errors->", data.errors);
            }

        });

    });

});

HTML(片段,因为它是一种模式)

<div class="modal" id="modal-create">
    <div class="modal-background" onclick="modal('#modal-create', 'close');"></div>
    <div class="modal-content">
        <div id="modal-create-results"></div>
        <h4 class="title is-4">
            Create a Brand
        </h4>
        <form id="create_brand" name="create_brand" class="form" novalidate="">
            <div class="field is-horizontal">
                {{ Form::label("name", "Name", ["class" => "field-label is-normal"]) }}
                <div class="field-body">
                    <div class="field">
                        <p class="control">
                            {{ Form::text('name', null, ["class" => "input", "id" => "name", "required" => "required", "autofocus" => "autofocus"]) }}
                        </p>
                    </div>
                </div>
            </div>
            <div class="field is-horizontal">
                {{ Form::label("contact", "Contact", ["class" => "field-label is-normal"]) }}
                <div class="field-body">
                    <div class="field">
                        <p class="control">
                            {{ Form::text('contact', null, ["class" => "input", "id" => "contact"]) }}
                        </p>
                    </div>
                </div>
            </div>
            <div class="field is-horizontal">
                {{ Form::label("email", "Email", ["class" => "field-label is-normal"]) }}
                <div class="field-body">
                    <div class="field">
                        <p class="control">
                            {{ Form::email('email', null, ["class" => "input", "id" => "email"]) }}
                        </p>
                    </div>
                </div>
            </div>
            <div class="field is-horizontal">
                {{ Form::label("phone", "Phone", ["class" => "field-label is-normal"]) }}
                <div class="field-body">
                    <div class="field">
                        <p class="control">
                            {{ Form::text('phone', null, ["class" => "input", "id" => "phone"]) }}
                        </p>
                    </div>
                </div>
            </div>
            <div class="field is-horizontal">
                <p class="control is-grouped">
                    {{ Form::button("Save", ["type" => "submit", "class" => "button is-stenton", "id" => "save"]) }}
                    <a class="button" onclick="modal('#modal-create', 'close');">Cancel</a>
                </p>
            </div>
        </form>
    </div>
    <button class="modal-close" onclick="modal('#modal-create', 'close');"></button>
</div>

<meta name="_token" content="{{ csrf_token() }}" />
{{ Html::script('js/brands/create_ajax.js') }}

【问题讨论】:

  • 您是否尝试过在 ajax 帖子设置中使用完整的 url?也尝试使用像这样的数据data: { name: name, contact: contact, email: email, phone: phone, },
  • 响应总是成功吗?
  • @AntonisTsimourtos 我试过了,但没用。
  • @PankajMakwana 它总是会成功。我在下面使用了 apkryfos 的方法,它奏效了。
  • 您收到验证消息了吗?

标签: javascript php jquery ajax laravel


【解决方案1】:

响应总是成功的,因为您总是发送成功的响应,即使它包含错误。

你有三个选择:

1) 手动发送错误码

$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())  {
    //422 is the standard error code laravel uses for validation errors so we're going to keep it
    return \Response::json(array("errors" => $validator->getMessageBag()->toArray()),422);
}

2) 让 laravel 处理(推荐)

$this->validate($request,$rules); //Laravel will generate the appropriate error exception response

*$this-&gt;validate来自特征ValidatesRequests

3) 不推荐:保持控制器代码不变并将 AJAX 代码更改为:

 $.ajax({

        type: type,
        url: url,
        data: formData,
        dataType: 'json',
        success: function (data) {
            if (data.errors) { /* errors happened */ } 
            else { /* no errors happened */ }
        }
 });

不推荐,因为在成功处理程序中处理错误是错误的。

【讨论】:

  • 我选择了#2,成功了!现在我可以通过添加 responseText 并调用它来捕获错误并显示它们。太感谢了! +1!
  • @WilliamDrake #2 是 laravel 建议的方式,所以这是一个很好的选择
  • 你知道我将如何实现类似的东西:foreach (xhr.responseText as error) { display_error_here }。现在我必须像这样检查: if (xhr.responseText["name"]) { // exists, display error } 为每个被验证的字段。
  • for (var key in xhr.responseText) { alert("Field:"+key+" has error "+ xhr.responseText[key]); } 甚至更好的$.each(xhr.responseText, function (key, value) { /* do stuff here */ });
  • 谢谢伙计。我最终赢得了 var obj = JSON.parse(xhr.responseText)["errors"];然后使用 $.each 显示值。干杯!
猜你喜欢
  • 2017-09-09
  • 1970-01-01
  • 2017-06-26
  • 2017-10-19
  • 2017-11-19
  • 2018-06-12
  • 2019-03-14
  • 2017-06-11
  • 2019-05-12
相关资源
最近更新 更多