これまでページ送りはサーバ側で行ってきたが、選択されたページ番号ごとの処理が新たなリクエストになり処理の度に項目数をカウントすることにならざるを得ない。
新たなリクエストに項目数などの情報をクッキーやGETリクエストのパラメータで引き継ぐことをすればよいのだが、ページ送りのためだけに大掛かりなことはしたくない。いろいろと調べているとJavaScriptを使えば端末側でページ送りができるので早速試してみた。
使ったのは、jquery pagination Plugin。
準備はjquery pagination Pluginに含まれるjquery.pagination.jsとpagination.cssを適当なフォルダーに入れておく。
ページ送りは全項目分のコンテンツを用意しておき、jquery.pagination.jsを使うことにより、ページ選択と必要項目の表示をしてくれる。それぞれの項目のコンテンツが小さい場合はこのような全項目を抱え込む方法でもよいが、画像などコンテンツの内容が大きい場合には全コンテンツを抱え込むのはサーバから端末側の情報転送だけでも時間がかかる。 そこで、選択されたページ番号から表示する項目インデックスだけをとりだし、このインデックスを基にページに表示する分だけの項目のコンテンツを得て表示する方法にした。
ソースコード
<script type="text/javascript">
var per_page;
var num_entries;
var result;
var node;
/* ページ選択時に実行する関数 */
function pageselectCallback(page_index, jq){
var page_no = page_index + 1 ;
var item_start = page_index * per_page;
var item_last = (page_index + 1) * per_page - 1 ;
if(item_last>=num_entries) {
item_last = num_entries - 1;
}
var opt = jQuery('#Searchresult');
opt.empty();
opt.append('ページ番号:' + page_no +
'<br>' + '開始項目インデックス:' + item_start +
'<br>' + '終了項目インデックス:' + item_last);
result.empty();
var count = 0;
var div_vew = 0;
var img;
var ank;
var div = jQuery('<div>').attr('class','view');
for(var i = item_start;i<=item_last; i++){
ank = jQuery('<a>').attr('href',nodes[i]['path'])
.attr('rel','lightbox[group]');
img = jQuery('<img>').attr('class','view')
.attr('src',nodes[i]['path'])
.attr('width',150)
.attr('height',150);
ank.append(img);
div.append(ank);
count++;
if(count%4==0) {
result.append(div);
div = jQuery('<div>').attr('class','view');
div_vew = 1;
}
else{
div_vew = 0;
}
} /* end for */
if(!div_vew){
result.append(div);
}
return false;
}
/* 初期処理関数 */
function initPagination(page,url) {
per_page = page;
var http = new JKL.ParseXML( url );
var doc = http.parse();
result = jQuery('#result');
result.empty();
// 結果XMLから<customer>要素を取得
nodes = doc['root']['customer'];
if(nodes.length == 0) { /* 登録結果が0件だった場合 */
result.append('登録件数は0件でした。');
}
num_entries = nodes.length; /* 項目数を設定 */
jQuery("#Pagination").pagination(num_entries, {
callback: pageselectCallback,
items_per_page:per_page,
next_text:"次へ>>",
prev_text:"<<前へ",
num_display_entries:5,
num_edge_entries:1,
ellipse_text:"・・"
});
}
jQuery(document).ready(function(){
url = 'http://sample.sakuraweb.com/java6/filedef.xml';
initPagination(3,url);
});
</script>
<h1>jQuery Pagination 試験</h1>
<div id="Pagination"></div>
<br style="clear:both;">
<div id="Searchresult">
This content will be replaced when pagination inits.
</div>
<hr>
<div id="result">
ここに結果をいれる
</div>
サンプル
jQuery Pagination 試験
This content will be replaced when pagination inits.
ここに結果をいれる