【问题标题】:How to use variable data after Ajax Call Success - LaravelAjax 调用成功后如何使用变量数据 - Laravel
【发布时间】:2017-12-18 10:42:12
【问题描述】:

我创建了一个小型文件管理器来管理我的文件。一方面,通过 JsTree 显示了文件夹结构。在右侧,我希望根据单击左侧文件夹显示该文件夹中包含的文件。 单击时会进行 Ajax 调用,该调用调用 selectFiles 方法来遍历路由。现在在控制台中我看到了正确的数据,但我不知道如何将它用于刀片中的 foreach。

AJAX:

// chiamata Ajax per selezionare files in base all'id
$('#treeview').on("select_node.jstree", function (e, data) {
    var id = data.node.id;
    $.ajax({
        type: 'POST',
        url: 'archivio_documenti/+id+/selectFiles',
        data: {id:id},
        success: function(data) {
            console.log('Succes!',data);
        },
        error : function(err) {
            console.log('Error!', err);
        },
    });
});

DocumentiController.php:

/**
 * Selzionare files in base all'id della cartella
 */
public function selectFiles(Request $request){
    try{
        $id = $request->id;
        $files = \App\Documento::where('cartella_id',$id)->get();

        return response()->json(compact('files'));

    }
    catch(\Exception $e){
        echo json_encode($e->getMessage());
    }
}

路线:

Route::post('archivio_documenti/{id}/selectFiles', 'DocumentiController@selectFiles');

更新:

                    @foreach($files as $key => $file)
                        <div id="myDIV" class="file-box">
                            <div class="file">

                                {!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
                                <button type="submit" class="#" style="background: none; border: none; color: red;">
                                    <i class='fa fa-trash' aria-hidden='true'></i>
                                </button>
                                {!! Form::close() !!}

                                <a href="/documento/{{ $file->id }}/edit" class="#" role="button" style="text-align: center;"><i class='fa fa-edit' aria-hidden='true'></i></a>

                                <input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
                                <a href="#"><i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i></a>

                                <a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
                                    <span class="corner"></span>

                                    <div class="icon">
                                        <i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
                                    </div>
                                    <div class="file-name">
                                        {{$file->file}}
                                        <br>
                                        <small>Update: {{$file->updated_at}}</small>
                                    </div>
                                </a>
                            </div>
                        </div>
                    @endforeach

【问题讨论】:

  • 这是一个 javascript 响应,因此您需要操作 DOM 以将结果添加到视图中。 jQuery 有一些方法——比如 append()prepend() 可以帮助你。
  • @lesssugar 可以将文件变量直接发送到刀片中吗?我有使用变量 $files 的 @foreach()。
  • 请告诉我们您的foreach
  • @lesssugar 我更新了我的代码。

标签: ajax laravel laravel-5


【解决方案1】:

好的,你的 foreach 有点复杂,但想法本身很简单:用 JavaScript 从你的 Blade 重新创建 foreach 循环并将结果附加到 DOM。

在您的 success 回调中,您可以例如这样做:

$('#treeview').on("select_node.jstree", function (e, data) {
    var id = data.node.id;
    $.ajax({
        type: 'POST',
        url: 'archivio_documenti/+id+/selectFiles',
        data: {id:id},
        success: function(data) {

            // Build the HTML based on the files data

            var html = '';

            $.each(data, function(i, file) {
                html += '<div class="file" id="file_' + file.id + '">' + file.updated_at + '</div>';
            });

            // Append the built HTML to a DOM element of your choice

            $('#myFilesContainer').empty().append(html);

        },
        error : function(err) {
            console.log('Error!', err);
        },
    });
});

显然,这是简化的,您需要使用您在上面的 foreach 循环中向我们展示的 HTML 结构,但想法是相同的:(1) 循环遍历 data 中的文件对象并逐行构建 HTML 结构,(2) 将整个 HTML 块放入 DOM 中,用户单击文件夹后需要显示的任何位置。

替代方案:

如果您想将 foreach 循环保留在 Blade 中而不是 Javascipt 中,您可以将循环移动到单独的刀片中:

folder_contents.blade.php

@foreach($files as $key => $file)
                        <div id="myDIV" class="file-box">
                            <div class="file">

                                {!! Form::open(['method' => 'DELETE','route' => ['documento.destroy', $file->id]]) !!}
                                <button type="submit" class="#" style="background: none; border: none; color: red;">
                                    <i class='fa fa-trash' aria-hidden='true'></i>
                                </button>
                                {!! Form::close() !!}

                                <a href="/documento/{{ $file->id }}/edit" class="#" role="button" style="text-align: center;"><i class='fa fa-edit' aria-hidden='true'></i></a>

                                <input id="myInput_{{$key}}" type="text" value="{{'project.dev/'.$file->path.'/'.$file->file}}">
                                <a href="#"><i class="btnFiles fa fa-files-o" aria-hidden="true" data-id="{{$key}}"></i></a>

                                <a href="{{' http://project.dev/'.$file->path.'/'.$file->file}}">
                                    <span class="corner"></span>

                                    <div class="icon">
                                        <i class="img-responsive fa fa-{{$file->tipo_file}}" style="color:{{$file->color_file}}"></i>
                                    </div>
                                    <div class="file-name">
                                        {{$file->file}}
                                        <br>
                                        <small>Update: {{$file->updated_at}}</small>
                                    </div>
                                </a>
                            </div>
                        </div>
                    @endforeach

然后,在您的控制器中:

public function selectFiles(Request $request){
    try{
        $id = $request->id;
        $files = \App\Documento::where('cartella_id',$id)->get();

        // Save the view as string
        $view = view('folder_contents.blade.php', compact('files')))->render();

        // Pass the ready HTML back to Javasctipt
        return response()->json(compact('view'));

    }
    catch(\Exception $e){
        echo json_encode($e->getMessage());
    }
}

【讨论】:

    【解决方案2】:

    你必须为ajax设置标题

    headers: {
            'X_CSRF_TOKEN':'xxxxxxxxxxxxxxxxxxxx',
            'Content-Type':'application/json'
        },
    

    在控制器中

    public function selectFiles(Request $request){
        try{
    
            $id = $request->id;
    
            $files = \App\Documento::where('cartella_id',$id)->get();
    
            return response()->json($files);
    
        }
        catch(\Exception $e){
            echo json_encode($e->getMessage());
        }
    }
    

    【讨论】:

    • 请正确阅读问题,这不是正确的答案。
    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2017-11-16
    • 2021-05-16
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多