【问题标题】:Laravel 5.2 return with errors - how to tell which form is submittedLaravel 5.2 返回错误 - 如何判断提交了哪个表单
【发布时间】:2016-10-29 05:18:25
【问题描述】:

我正在使用 Laravel 5.2。在我的索引页面上,我有一个添加新条目的按钮,它会在灯箱中显示表单。然后这个表单通过 create 方法提交。

我还列出了此页面上的每个条目,可以内联编辑它们,通过更新方法提交。

我已通过请求设置验证。这意味着当有人在添加时遗漏了某些内容时,它会重定向到 index 方法并出现错误。但是,仅当用户触发灯箱时才会显示错误。

我知道我可以使用$errors 来查看任何错误,但我不知道如何区分创建和更新表单以强制灯箱在重新加载时出现创建错误。有没有办法做到这一点?

更新:

有人建议使用 AJAX 绕过重新加载问题,但现在我得到了 422 返回:

AJAX 调用:

(function(){
    var submitAjaxRequest = function(e){
        var form = $(this);
        var method = form.find('input[name="_method"]').val() || 'POST';

        $.ajax({
            type: method,
            url: form.prop('action'),
            data: form.serialize(),
            success: function(data){
                console.log(data)
            }
        });

        e.preventDefault();
    }
    $('form[data-remote]').on('submit', submitAjaxRequest);
})();

请求:

public function response(array $errors)
{
    $response = parent::response($errors);

    if ($this->ajax() || $this->wantsJson()) {
        return $response;
    }

    return $response->with('requestMethod', $this->method());
}

我还测试了 ajax 调用,当满足验证规则时它可以正常工作。仅当验证返回输入错误时才会失败。

【问题讨论】:

  • 您能否提供更多信息,请求、表单和控制器的代码 sn-ps 将非常有用。
  • 你能用ajax吗?这样您就不必担心重新加载。
  • @Ross Wilson - 通过消除问题,ajax 可能是最简单的解决方案。我想知道在我使用它之前是否有另一种方法来区分表单..
  • @RossWilson - ajax 无法正常工作,因为我正在使用验证请求,所以当未填写必填字段时,我得到的是 422 (Unprocessable Entity) 返回而不是预期的错误反馈
  • error: function(response) { console.log(response);} 添加到您的 ajax 调用中,您将看到如何访问错误。

标签: php laravel-5.2


【解决方案1】:

您可以覆盖response 方法,以便您可以刷新请求的类型。

你可以在 Request 类中添加

    public function response(array $errors)
{
    $response = parent::response($errors);

    if ($this->ajax() || $this->wantsJson()) {
        return $response;
    }

    return $response->with('requestMethod', $this->method());
}

(使用 ajax,您无需担心页面重新加载,因此我们可以返回原始响应。)

在上面我假设您使用POST 作为创建方法,使用PUTPATH 作为更新方法。如果不是这种情况,您可以使用一种对您有意义的方式来区分请求。

那么在您看来,您可以执行以下操作:

@if(session('requestMethod') == 'POST')

https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data

如果您要使用 ajax,正如我在上面的评论中提到的,您需要确保在 ajax 调用中使用错误方法:

$.ajax({
    type: method,
    url: form.prop('action'),
    data: form.serialize(),
    success: function (data) {
        console.log('success', data)
    },
    error: function (data) {
        console.log('error', data)
    }
});

希望这会有所帮助!

【讨论】:

  • concept 可以做到,但我在实施时遇到了问题。我已将您的代码复制到我的 EntryRequest 文件中,位于 rules()` 函数下方。我还在表单中使用了正确的 POSTPUT 方法。仍然收到 422 响应。我还尝试将 return $response; 从 if 语句中移出以进行测试,无论是否使用 ajax 调用,都没有变化。
猜你喜欢
  • 2010-10-18
  • 2011-02-10
  • 2016-11-19
  • 2013-10-09
  • 2016-06-14
  • 2020-11-18
  • 2012-02-22
  • 2011-05-30
  • 2016-05-20
相关资源
最近更新 更多