【问题标题】:ajax to delete a record from database does not fire redirect in laravel从数据库中删除记录的ajax不会在laravel中触发重定向
【发布时间】:2020-01-30 16:34:33
【问题描述】:

我正在使用 ajax 请求从我的数据库中删除一条记录。这有效并删除了记录,但是它不会使用成功消息重定向用户。

我正在使用 sweetalert 模态显示确认删除按钮,当您单击“是”时,模态消失并且记录已被删除,但页面不会重定向并且记录不会消失,直到您刷新页面。

这似乎被忽略了 -

return redirect()->route('users.index')->with('success', 'User deleted!');

AJAX -

<script>
 $(document).ready(function() { 
  $(".swal2-confirm").click(function(){
    var id = '{{ request()->delete_id }}';
    var route = '{{ request()->route }}';
    $.ajax({
      type:'post',
      url:'/admin/' + route + '/' + id,
      dataType: 'json',
      headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
      data: {'_method':'delete', "_token": "{{ csrf_token() }}", id:id},
    });
  });
});
</script>

控制器 -

public function destroy($id)
    {
      //Delete user from database
      User::find($id)->delete();

      return redirect()->route('users.index')->with('success', 'User deleted!');
    }

【问题讨论】:

  • 你应该像return response(['url' =&gt; route('user.index')], 200)一样返回json响应,然后在你的ajax成功部分你可以这样做window.location.href = data.url
  • 如果您使用 ajax 调用它不会将您重定向到该页面,您需要发送成功状态以响应 ajax 调用,然后重新加载页面 location.reload();或者代替 ajax 只是简单地使用 url 来调用删除函数,这样它就可以在你编写代码时工作

标签: php ajax laravel sweetalert2


【解决方案1】:

我已经通过显示警报然后在我的 ajax 中重新加载页面来解决这个问题 -

<script>
$(document).ready(function () {
  $(".swal2-confirm").click(function () {
    var id = '{{ $delete_id }}';
    $.ajax({
      type: 'post',
      url: '/admin/users' + '/' + id,
      dataType: 'json',
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
      data: { '_method': 'delete', "_token": "{{ csrf_token() }}", id: id },
      complete: function () {
        swal.fire({
          type: 'success',
          title: 'User Deleted!',
          showConfirmButton: false,
          timer: 2500
        });
        setTimeout(function () { window.location.replace('/admin/users') }, 2500);
      }
    });
  });
});
</script>

【讨论】:

  • 这实际上是我在互联网上看到的最简单的方法。
猜你喜欢
  • 2016-10-16
  • 2013-05-05
  • 2020-03-06
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 2021-09-18
相关资源
最近更新 更多