如何在php中的产品网格中显示ajax响应?

时间:2017-09-16 06:21:01

标签: php jquery ajax laravel laravel-5

我有一个产品网格,最初显示网格中的产品列表。当我按类别搜索产品时,使用ajax调用我想只显示网格内该类别的产品。如何输出此回复?

产品网格:

     <div class="col-sm-9">    
           @foreach($products as $product)          
              <div class="col-md-4">
                 <div class="products-gallery">       
                    <h4>{{$product->name}}</h4>                              
                 </div>  
              </div> 
            @endforeach                                                 
        </div> 

这是我的javascript部分:

    jQuery('#searchId').on('change', function()
        {
          var category_id = jQuery(this).val() 
          searchProduct(category_id)    
        })

        function searchProduct(category_id)
              {  
                $.ajax({
                    method: 'get', 
                    url: "{{url('searchByCategory')}}", 
                    data: {'category_id' : category_id}, 
                    success: function(html){                   
                        $(".col-sm-9").html(html)            
                    },
                    error: function(jqXHR, textStatus, errorThrown) { 
                        console.log(JSON.stringify(jqXHR));
                        console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                    }
                    });                        
              }

这是我的ajax回复:

[{…}]
0:

category_id:3
created_at:"2017-09-11 20:33:19"
id:4
name:"HT 400 Triplex "
updated_at:"2017-09-11 20:33:19"

1 个答案:

答案 0 :(得分:1)

$(document).on('submit', 'form#yourFormID', function(event) {
    event.preventDefault();

    $.ajax({
        url: '/route/url',
        type: 'GET',
        dataType: 'html',
        data: {firstValue: 'foo', secondValue: 'bar'},
        success: function(html){
           $(".col-sm-9").html(html)
           //OR $(".col-sm-9").load(/route/url);
        }
    });


});


//route
Route::get('/route/url', 'ControllerName@fetchDataAction');

//Controller
public function fetchDataAction(Request $request){

    $data = ModelName::where('foo', $request->get('firstValue'))->where('bar', $request->get('secondValue'));

    return view('result', ['products' => $data]);
}

//result.blade.php
@foreach($products as $product)          
          <div class="col-md-4">
             <div class="products-gallery">       
                <h4>{{$product->name}}</h4>                              
             </div>  
          </div> 
        @endforeach

那应该可以得到你想要的结果。