从json feed加载更多文章

时间:2013-03-08 12:15:20

标签: jquery ajax

我需要你帮助一些ajax / jquery请求从json feed加载更多的文章。

$(document).ready(function () {
var output = $('#news');
var count = "2";
var page = "1";
$.ajax({
    url: 'http://domain.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) {
            var news = '<li>' + item.title + '</li>';
            output.append(news);
        });

        if (data !== undefined && data !== undefined) {
            $('#stats').append('Page ' + page + ' of ' + data.pages + ' | Total posts ' + data.count_total + '');
        }

    },
    error: function () {
        output.html('<h1 class="error">There was an error loading the data.</h2>');
    }
});
});

我需要的是:点击链接(加载更多)页面应该显示“var page ='2'”中的标题,依此类推但当它到达最后一页时,链接应该消失。希望它确实有意义。

请看下面的小提琴: http://jsfiddle.net/AGGjj/

提前多多感谢。

2 个答案:

答案 0 :(得分:2)

对于每个有答案的人来说:

$(document).ready(function () {

var output = $('#news');
var count = "2";
var page = "1";
var load = function() {
$.ajax({
    url: 'http://domain.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>');
    }
});
};
//add click handler
$('#loadmore').click(function() {load();});
//load first page
$('#loadmore').trigger('click');
//or
load();
});

答案 1 :(得分:0)

在成功功能结束时添加

success: function (data, status) {
    $.each(data.posts, function (i, item) {
        var news = '<li>' + item.title + '</li>';
        output.append(news);
    });

    if (data !== undefined && data !== undefined) {
        $('#stats').append('Page ' + page + ' of ' + data.pages + ' | Total posts ' + data.count_total + '');
    //just test if the current page is the last one
    if(page == data.pages) {
       $('link selector').hide();
       or remove
       $('link selector').remove();

    }
    }

},