【问题标题】:Chaining 'with' statements while returning view返回视图时链接“with”语句
【发布时间】:2019-06-20 13:33:38
【问题描述】:

所以在其中一个 Ajax 调用中,我想用一些数据返回页面的索引视图,同时还发送其他数据 - 消息。

索引视图看起来像这样:

public function index()
{
    // data retrieval

    $data = [
        'groups' => $groups,
        'info' => $info,

    ];
    return view('groups.index')->with('data', $data);
}

现在有了这个 Ajax 调用

$(document).ready(function(){
    $('.group-delete-fa').click(function() {
        if (confirm('Remove user?')) {
            var id = $(this).attr('id');
            var idGroup = $(this).attr('value');
            $.ajax({
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                method: "POST",
                url: "/remove_user",
                data: {id: id, idGroup: idGroup },
                success: function(response) {
                    $('body').html(response);
                    $('.dropdown-toggle').dropdown();

                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { 
                    //alert(errorThrown);
                }       
            });
        }
    })
});

我调用这个函数

public function removeUser(Request $request) {
    $id = $request->id;
    $idGroup = $request->idGroup;
    $user = User::find($id);

    //$user->groups()->detach($idGroup);

    $view = $this->show($idGroup);
    return $view->with('success', 'User  removed from group')->render();
}

消息解析如下(在根 jumbotron 元素中):

@if (session('success'))
    <div class="alert alert-success">
        {{session('success')}}
    </div>
@endif

但是,消息不会与$data 一起发送,也不会被解析。我猜你不能像这样链接with() 函数?如何发送其他数据?

感谢您的帮助。

【问题讨论】:

    标签: php ajax laravel laravel-blade


    【解决方案1】:
    1. 您将success 作为变量传递给视图,而不是在会话中。 尝试更改您的根 jumbotron 元素 session('success')$success,首先使用 isset 检查它是否存在。
        @if (isset($success))
            <div class="alert alert-success">
                {{$success}}
            </div>
        @endif
    
    1. 或者不要使用 ajax 并重定向到与会话中的消息相同的页面。

    【讨论】:

    • 是的,就是这样,甚至不知道我为什么在那里使用会话。谢谢。
    【解决方案2】:

    好的,所以我这样做了:

    return redirect('/groups/' . $idGroup)->with('success', 'User removed from the group.');
    

    哪种方法可行,但如果您使用 Ajax,这是一种好方法吗?

    【讨论】:

      猜你喜欢
      • 2017-09-23
      • 1970-01-01
      • 2012-05-10
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多