如何在Ajax Call Success之后使用可变数据 - Laravel

时间:2017-12-18 10:42:12

标签: ajax laravel laravel-5

我创建了一个小文件管理器来管理我的文件。一方面,感谢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

2 个答案:

答案 0 :(得分:1)

你必须为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());
    }
}

答案 1 :(得分:0)

好的,你的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());
    }
}