【问题标题】:Laravel redirect to route from controller when called by AJAX当被 AJAX 调用时,Laravel 重定向到来自控制器的路由
【发布时间】:2014-02-06 11:44:55
【问题描述】:

鉴于这块ajax 调用FriendsController@destroy

$.ajax({
    url:     '/dashboard/friends/' + id,
    type:    'DELETE',
    data:    { src: 'show' },
    success: function(response) {
    }
});

删除过程完成后,我如何在FriendsController 中return Redirect::route('dashboard.friends.index')?我想这是试图将响应返回给不知道如何反应的 AJAX。

我可以window.location.href = '/dashboard/friends',但我想向视图发送一条成功消息,而我无法使用 AJAX。

【问题讨论】:

  • 为什么不在success函数中闪现你的成功信息,然后等待3秒再用window.location.href = '/dashboard/friends'重定向?

标签: php laravel


【解决方案1】:

我找到了最简单的方法。 只需在您的 ajax 成功中再次使用相同的 url。假设朋友是你的路线名称,那么

$.ajax({
    url:     '/dashboard/friends/' + id,
    type:    'DELETE',
    data:    { src: 'show' },
    success: function(response) {
       window.location.href = "friends";
    }
});

这样,您可以根据需要放置重定向或闪存会话消息。

【讨论】:

    【解决方案2】:

    Here is how I solved this issue 我自己。对于模型的AJAX删除等功能,会提示确认模态,执行删除,闪现消息并重定向到提供的路由。

    设置完成后,可以通过将正确的data 属性传递给原始删除按钮或链接来动态完成。

    【讨论】:

      【解决方案3】:

      我知道这可能是个老问题,但如果你想返回动态路线

      return route('post.view', ['id' => $result]);

      在你的前端你会做

        success: function(response){
                window.location.replace(response);
                }
      

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题,这就是我的窍门。

        在您的控制器中,您可以使用以下命令闪烁消息:

        \Session::flash('success', __('locale.message'));

        然后在你的 ajax 响应处理程序中,你重定向到你想要的任何地方

        location.replace('/home');

        不要忘记在视图中添加登录以显示消息,即:

         @if (session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session('success') }}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
         @endif
        

        【讨论】:

          【解决方案5】:
          if(data.success){
          
              var loc = window.location;
              window.location = loc.protocol+"//"+loc.hostname+"/admin/dashboard";
          }
          

          【讨论】:

            猜你喜欢
            • 2019-03-16
            • 2017-08-03
            • 2016-06-15
            • 2017-12-12
            • 1970-01-01
            • 1970-01-01
            • 2017-12-06
            • 2020-11-22
            • 2020-08-23
            相关资源
            最近更新 更多