How to show more list using jquery

感情迁移 提交于 2019-11-30 15:33:52

In principle, you want a container where to place all the newly fetched messages.

<div id="messages">
    <! -- message 1 -->
    <! -- message 2 -->
    <div id="newMessages">
    </div>
</div>

Then you want a button (or anchor, or whatever) that you can hook up to a fetch-more-method:

<input type="button" value="Fetch more messages" id="btnFetchMessages" />

Place the hookup somewhere inside DOMReady:

var lastFetchedMessage = 0;

$('#btnFetchMessages').click(function() {
    $.ajax({
        url: '/getMessages.php',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: '{"lastId":'+lastFetchedMesasge+'"}',
        success: newMessagesReceived
});

So on a click of the button we submit an AJAX request to getMessages.php where you'll look at the lastFetchedMessage and return the 10 or so next messages based upon that. From that page, you return a JSON array containing the messages, with all their info that you're interested in.

Upon a successful AJAX reques, the funciton newMessagesReceived will be called:

function newMessagesReceived(result) {
    var container = $('#newMessages');

    for(var i = 0; i < result.length; i++) {
        var message = $('<div>' + result[i].body + '</div>');
        container.append(message);
    }

    var lastFetchedMessage = result[i].id;
}

The above assumes that you return an array with messages, that have at least the properties body and id:

[ { "body": "new message1", "id": "10" }, { "body": "new message2", "id": "11" } ]

In my latest project, I use jQuery tools scrollable to display 20 newest item in a list (<ul><li>). When the list scrolled to the last page, I fetch next 20 items, then append it to the end of the list, using build in jquery tools api. This will go on until the AJAX request return empty result, that indicate no more list in the database. I have a variable as a flag, then I set it to false, so no AJAX request fired when the list scrolled to the last page.

You may see it looks like twitter home page, but without 'more' link, since the list appended automatically.

Unfortunately right now the project still in alpha, so I cannot show it here. You may try it and post your code here, and I will help you tweak it.

Use javascript to hold state information about how many rows are being displayed, etc.

Have the button invoke a JS function that returns data via ajax. The result from the ajax call can be HTML and injected into a div tag. The JS function needs to update the state information (increasing the # of rows each time, etc), and passes that state info to the ajax call.

The target of the ajax call can be a PHP script that does the MySQL query and generates the HTML which is passed back.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!