1

我需要一些 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/

提前非常感谢。

4

2 回答 2

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();
});
于 2013-03-08T13:08:38.437 回答
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();

    }
    }

},
于 2013-03-08T12:19:34.487 回答