2016-11-21 63 views
1

我目前正在研究一個應用程序,我將調用一個url並獲取JSON response.i使用Handlebars.js創建一個列表li,最後將其附加到ul。因爲json響應很大,所以需要以分頁格式顯示數據。你們請指導我如何以分頁格式顯示li。如何分頁json響應數據

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title> Pagniate json data </title> 
 
\t <!-- Latest compiled and minified Bootstrap CSS --> 
 
\t <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
 
</head> 
 
<body> 
 

 
    <div class="container-fluid"> 
 
     <div class="row"> 
 
     <div class="col-md-6"> 
 
\t \t \t <ul class="list-group"> 
 

 
\t \t \t </ul> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    
 

 
\t <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
\t <!-- Latest compiled and minified Bootstrap JavaScript --> 
 
\t <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> \t 
 
\t <!-- Handlebars.js --> 
 
\t <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script> 
 
    <!-- Handlebar Template for creating the list --> 
 
\t <script id="list-group-item-template" type="text/template" > 
 
\t  {{#each this}} 
 
     <li class="list-group-item"> {{ title }} </li> 
 
     {{/each}} 
 
\t </script> 
 
\t <script> 
 
\t $(document).ready(function(){ 
 
\t  \t $.ajax({ 
 
      method:"GET", 
 
      url:"http://starlord.hackerearth.com/cognizantinternal/hackernews", 
 
      success:function(data){ 
 
        //removing the first element from the response array 
 
        data.shift(); 
 
        var template = Handlebars.compile($('#list-group-item-template').html()); 
 
        var list = template(data); 
 
        $('.list-group').append(list); 
 
      } 
 
\t  \t }); 
 
\t }); 
 
\t </script> 
 
</body> 
 
</html>

+0

如果響應很大,那麼在客戶端分頁並不會加快速度 - 您需要在服務器上進行分頁 –

回答

1

在這種情況下,它會更好做在服務器端分頁。否則,您可以將json存儲在本地存儲中並執行分頁。完成此請求後清除本地存儲

1

IMO,您應該將您發送給服務器的請求分頁(例如,在發送AJAX請求時提供限制n,通常作爲查詢參數)。

然後,提供一個Load More按鈕來向服務器發送另一個請求,或者當用戶向下滾動到頁面底部時再次獲取數據。