【问题标题】:how to show error with laravel and ajax in views如何在视图中显示 laravel 和 ajax 的错误
【发布时间】:2017-09-28 04:45:44
【问题描述】:

在 laravel 中显示错误时遇到问题。我正在使用 ajax 将请求表单从客户端发送到服务器并向后发送。这是我的 ajax 代码,似乎函数 append() 不起作用。

$('#petition-form').on('submit', function(e) {
  e.preventDefault();
  var formdata = new FormData($(this)[0]);
  formdata.append('content', tinymce.get('content').getContent());
  $.ajax({
    url: $(this).attr('action'),
    data: formdata,
    processData: false,
    contentType: false,
    cache: false,
    method: 'POST'  
  }).done(function(response) {
   window.location.href = response.slug;
 }).fail(function(response) {
   $(this).append(response);
});
});

这是我的看法

@if (count($errors) > 0)
<div class="alert alert-danger">
    <ul>
        @foreach ($errors->all() as $error)
        <li>
            {{ $error }}
        </li>
        @endforeach
    </ul>
</div>
@endif

所以有人帮我解决这个问题!谢谢

【问题讨论】:

  • $(this) 可能是 fail 回调中的不同对象。尝试将$(this) 保存到回调外部的变量中,然后改用该变量。

标签: php jquery ajax laravel-5


【解决方案1】:

尝试这样的事情 - 设置存储对 $(this) 的引用的 self 变量:

$('#petition-form').on('submit', function(event) {
    event.preventDefault();
    var self = $(this),
        formData = new FormData(self[0]);
    formData.append('content', tinymce.get('content').getContent());
    $.ajax({
        url: self.attr('action'),
        data: formData,
        processData: false,
        contentType: false,
        cache: false,
        method: 'POST'
    }).done(function(response) {
        window.location.href = response.slug;
    }).fail(function(response) {
        self.append(response);
    });
});

然后您可以从您的视图中删除$errors 引用,我可能会prepend 验证消息而不是append 以确保它们显示在表单上方,但这只是偏好问题。

【讨论】:

  • 它仍然无法正常工作。也许我必须使用 parseJSON??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 2018-02-23
  • 1970-01-01
  • 2020-10-04
  • 2020-05-01
  • 1970-01-01
相关资源
最近更新 更多