「jquery入門」ajaxでページングを実現するサンプルコード

サンプルコード:
$(document).ready(function () {
var output = $('#news’);
var count = “2";
var page = “1";
var load = function() {
$.ajax({
url: 'http://sample.com/api/get_recent_posts/?post_type=news&count=’ + count + '&page=’ + page + '&callback=?’,
async: false,
callback: 'callback’,
crossDomain: true,
contentType: 'application/json; charset=utf-8’,
type: 'POST’,
dataType: 'jsonp’,
timeout: 5000,
success: function (data, status) {
$.each(data.posts, function (i, item) {
output.append($('<li />’).text(item.title));
});

if (data !== undefined && data !== undefined) {
$('#stats’).text('Page ' + page + ' of ' + data.pages + ' | Total posts ' + data.count_total + ");
}
if (page == data.pages) {
$(“#loadmore").remove();
}
page++;

},
error: function () {
output.html('<h2 class="error">There was an error loading the data.</h2>’);
}
});
};
//クリックハンドラを追加
$('#loadmore’).click(function() {load();});
//load first page
$('#loadmore’).trigger('click’);
//or
load();
});

JavaScript

Posted by arkgame