如何在Laravel中使用通过Ajax接收的响应而不在控制器中编写HTML

时间:2019-05-15 10:00:17

标签: jquery ajax laravel

我主要是尝试从HTML中的ajax响应转换数据,我读过每个人都在控制器中编写HTML代码的文章,但我很困惑,我们不应该在控制器中编写任何类型的HTML。我在控制器中编写了HTML,但对这种编程不满意。我如何获得响应以及获得什么格式,以便我可以用JSON或其他形式接收的HTML中对该响应进行编码。 在视图m中显示制造商列表。不用在控制器中编写HTML的任何更好的干净方法

查看


    <div class="pl-md-4 pl-2">
        {{count($leedManufacturers)}}
        <label class=" my-checkbox gry2">Show All Manufacturers
            <input type="checkbox">
            <span class="checkmark"></span>
        </label>
        @if(count($leedManufacturers) > 0 )

        @foreach($leedManufacturers as $leedsManufacturer)
        {{-- @foreach($leedManufacturers as $leedsManufacturer)  --}}
            <div class="post" id="post{{$leedsManufacturer['id']}}">
                <label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['name'], 300)}}
                        <input type="checkbox">
                        <span class="checkmark"></span>
                </label>
            </div>
            {{-- for load more script --}}
        {{-- <input type="hidden" id="row" value="0"> --}}

        {{-- <input type="hidden" id="all" value="{{$total_manufacturers}}"> --}}
        @endforeach

        @endif

        <button class="load-more" id="load" class="f-14 bold">See All</button>

        <input type="hidden" id="row" value="0">
        <input type="hidden" id="all" value="{{count($leedManufacturers)}}">


    </div>

脚本

<script type="text/javascript">

        // $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
            $(document).ready(function(){

            // Load more data
            $('.load-more').click(function(){
                var row = Number($('#row').val());
                var allcount = Number($('#all').val());
                var rowperpage = 3;
                // row = row + rowperpage;
                row = row + 3;

                if(row <= allcount){
                    $("#row").val(row);

                    $.ajax({
                    // url: "{{ route('ajax') }}",
                    url: "{{ url('ajax') }}",
                    type: 'post',

                    headers: {
                        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {row:row},

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

                    success: function(response){

                    // Setting little delay while displaying new content
                    setTimeout(function() {
                        // appending posts after last post with class="post"
                        $(".post").after(response).show().fadeIn("slow");

                        var rowno = row + 3;

                        // checking row value is greater than allcount or not
                        if(rowno > allcount){

                            // Change the text and background
                            $('.load-more').text("show less");
                            $('.load-more').css("background","darkorchid");
                        }else{
                            $(".load-more").text("Load more");
                        }
                    }, 2000);
                    }
 });

                }else{
            $('.load-more').text("Loading...");

            // Setting little delay while removing contents
            setTimeout(function() {

                // When row is greater than allcount then remove all class='post' element after 3 element
                $('.post:nth-child(3)').nextAll('.post').remove().fadeIn("slow");

                // Reset the value of row
                $("#row").val(0);

                // Change the text and background
                $('.load-more').text("Load more");
                $('.load-more').css("background","#15a9ce");

            }, 2000);
        }
            });

            });
    </script>

控制器:

public function ajax(Request $request){ 

    $data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();

    $html = '';

    foreach ($data['products'] as $product){

        $html .= '<div class="post" id="">';
        $html .= '<label class=" my-checkbox gry2" id="manufacturer">'.$product->name.'';
        $html .= '<input type="checkbox">';
        $html .= '<span class="checkmark"></span>';
        $html .= '</label>';
        $html .= '</div>';  
    }
    echo $html;
}

2 个答案:

答案 0 :(得分:0)

内部控制器的使用

public function ajax(Request $request){ 
    $products = Product::select('products.id', 'products.name', 'products.banner')->get();
    return view('ajax.product', compact('products'));
}

内部视图在我的案例中创建一个ajax视图views / ajax / product.blade.php 并使用此代码

@foreach ($products as $product){
    <div class="post" id="">
    <label class=" my-checkbox gry2" id="manufacturer">{{ $product->name }}
    <input type="checkbox">
    <span class="checkmark"></span>
    </label>
    </div>  
@endforech

答案 1 :(得分:0)

您可以在ajax中返回专用视图,并将其注入已经加载的视图中。

创建一个视图,例如ajax.blade.php

<div>
@foreach ($products as $product){
    <div class="post" id="">
        <label class=" my-checkbox gry2" id="manufacturer">{{ $product->name }}
          <input type="checkbox">
          <span class="checkmark"></span>
        </label>
    </div>  
@endforech
</div>

在控制器中,您可以检查ajax请求并返回渲染,这将返回可通过ajax注入html的原始html。

return view('views.ajax')->with('products', $products)->render();

然后在您的脚本中,您只需

success: fucntion(response){
  document.querySelector('#id').innerHTML = response
}