>本文演示瞭如何使用PHP,Ajax和JQuery輕鬆實現數據集的分頁,並利用Silex Framework的簡單性。
鍵優點:
pushState
id
>名稱example
people
年齡
1
jamie
43
>後端(帶有silex的PHP):>
使用Composer安裝Silex:composer require silex/silex
>
:使用PDO建立數據庫連接(建議安全和可移植性):index.php
<code class="language-php">$app['db'] = function () { $host = 'localhost'; $db_name = 'example'; $user = 'root'; $pass = ''; return new \PDO( "mysql:host={$host};dbname={$db_name}", $user, $pass, array(\PDO::ATTR_EMULATE_PREPARES => false) ); };</code>定義三個路線:
<code class="language-php">$app->get('/data/page/{page_num}/{rows_per_page}', function ($page_num, $rows_per_page) use ($app) { $start = ((int)$page_num - 1) * (int)$rows_per_page; $total_rows = (int)$rows_per_page; $stmt = $app['db']->prepare( 'SELECT `name` FROM `people` ORDER BY `name` LIMIT :from, :total_rows' ); $stmt->bindParam('from', $start); $stmt->bindParam('total_rows', $total_rows); $stmt->execute(); $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); return $app->json($result); });</code>
<code class="language-php">$app->get('/data/countrows', function () use ($app) { $stmt = $app['db']->query('SELECT COUNT(`id`) AS `total_rows` FROM `people`'); $result = $stmt->fetch(\PDO::FETCH_ASSOC); return $app->json($result); });</code>
<code class="language-php">$app->get('/', function () use ($app) { return file_get_contents(__DIR__.'/../resources/views/index.html'); });</code>
> frontend(html&jquery):
> JavaScript函數:
<code class="language-html"><ul id="rows"></ul> <ul id="page-numbers"></ul> </code>
<code class="language-javascript">var rows_per_page = 3; var total_rows; function initPageNumbers() { $.get('data/countrows', function(data){ total_rows = parseInt(data.total_rows); var count = 1; for(var x = 0; x < Math.ceil(total_rows / rows_per_page); x++) { $('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bpage-numbers').append('<li><a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b'+count+'" onclick="getPage('+count+');">'+count+'</a></li>'); count++; } }); } function getPage(page_num) { $('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15brows').html(''); $.get('data/page/'+page_num+'/'+rows_per_page, function(data){ $(data).each(function(){ $('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15brows').append('<li>'+this.name+'</li>'); }); }); } $(document).ready(function(){ initPageNumbers(); var page_num = 1; if(window.location.hash !== '') { var hash_num = parseInt(window.location.hash.substring(1)); if(hash_num > 0) { page_num = hash_num; } } getPage(page_num); });</code>
考慮:
>
>
以上是與JQuery,Ajax和PHP的分頁的詳細內容。更多資訊請關注PHP中文網其他相關文章!