2016-01-02 71 views
2

我正嘗試從laravel blade模板中的json響應創建分頁鏈接。我知道它可以創建使用PHP,但我怎麼能做到這一點從JSON響應。如何創建laravel blade中的json數據的分頁鏈接

這裏是我的控制器方法:

function getContact() 
{ 
    return $contacts = Contact::where(array('is_active'=>1)) 
         ->paginate(2); 
} 

,這裏是我的jQuery Ajax代碼顯示在表中的數據...

$.ajax({ 
      type:'GET', 
      url: '<?php echo URL::to('contactgroup/contact') ?>', 

      dataType: 'json',    
      success: function(data){ 
       //console.log(data['data'].length); 
      var table='<thead><th><input type="checkbox" id="checkAll" name="checkAll[]"/></th><th>Name</th><th>contact No</th></thead>'; 
      for(var i=0; i<data['data'].length; i++){ 
       table += '<tr><td><input type="checkbox" name="checkbox[]" class="individualCheckbox" value="'+data['data'][i].id+'"/></td><td>'+data['data'][i].contact_name+'</td><td>'+data['data'][i].primary_contact_no+'</td></tr>'; 

      } 
      $('#contactTable').empty(); 
      $('#contactTable').append(table); 
      } 
     }); 

和執行console.log是 -

JSON響應
{"total":3,"per_page":2,"current_page":1,"last_page":2,"next_page_url":"http:\/\/localhost\/smsapi\/public\/contactgroup\/contact\/?page=2","prev_page_url":null,"from":1,"to":2,"data":[{"id":1,"contact_name" 
:"M Islam","primary_contact_no":"017********","personal_email":"[email protected]","work_email" 
:"[email protected]","personal_phone":"017********","work_phone":"017********","personal_address":"abc","work_address":"ring road","is_active":1,"entry_by":7},{"id":4,"contact_name":"sdsdf","primary_contact_no":"242342","personal_email":"[email protected]","work_email":"[email protected]","personal_phone":"12142","work_phone":"fgbf","personal_address":"gfg","work_address":"fgfg" 
,"is_active":1,"entry_by":7}]} 

我可以使用上面的jQuery代碼顯示數據到表中,但我怎麼能顯示從分頁

使用jquery。

回答

1

在控制器

function getContact() 
{ 
    $contacts = Contact::where(array('is_active'=>1)) 
        ->paginate(2); 

    //return multiple value in JSON format 
    return \Response::JSON(array(
            'data'  => $contacts, 
            'pagination' => (string) $contacts->links() 
           ) 
         ); 
} 

在視圖

$.ajax({ 
     type:'GET', 
     url: '<?php echo URL::to('contactgroup/contact') ?>', 

     dataType: 'json',    
     success: function(data){ 
      //console.log(data['data'].length); 
     var table='<thead><th><input type="checkbox" id="checkAll" name="checkAll[]"/></th><th>Name</th><th>contact No</th></thead>'; 
     for(var i=0; i<data['data'].length; i++){ 
      table += '<tr><td><input type="checkbox" name="checkbox[]" class="individualCheckbox" value="'+data['data'][i].id+'"/></td><td>'+data['data'][i].contact_name+'</td><td>'+data['data'][i].primary_contact_no+'</td></tr>'; 

     } 
     $('#contactTable').empty(); 
     $('#contactTable').append(table); 
     $('#pagination').html(data['pagination']); //add this element in your HTML as well 
     } 
    }); 
+0

感謝@Ponce的回答,我增加的控制器編碼,但它返回數據[ '數據']爲{} –

+0

我編輯你的答案,讓其他人得到這個線程的完美解決方案,現在這個解決方案完全適合我。 –

相關問題