duanou3868 2013-07-03 08:09
浏览 31
已采纳

使用jQuery和AJAX从数据库中显示更多结果

I'm trying to create news block with AJAX in my template. so i wrote a simple code, in HTML Part:

<a href="javascript:ShowPost();">Show Posts</a>
<div id="result"></div>

jQuery Part:

function ShowPost(){
  $.post(dir + 'engine/ajax/posts.php', {action:"showpost"},
    function(data) {
      $("#result").html(data);
});
};

PHP Part:

if ($_POST['action'] == "showpost") {    
 $db->query( "SELECT title FROM post LIMIT 0,5 " );
  while ( $row = $db->get_row() ) {
   echo $row['title']."<br>";
  }    
}

Question is, how i can get more result after first click? for example, after first click on Show Posts link, i can show the 5 news from database. after second click on Show Posts link i need to show 6 to 10 news, in third click get result from 11 to 15 and continue ...

i hope you understand my question.

  • 写回答

3条回答 默认 最新

  • dongrouli2667 2013-07-03 08:13
    关注

    Based on your implementation you need to keep track how many items you have shown and pass the page number in. For example:

    jQuery Part:

    var pageNumber = 0; 
    function ShowPost() {   
       pageNumber++;   
       $.post(dir+ 'engine/ajax/posts.php', {action:"showpost", pageNum: pageNumber},
          function(data) {
           $("#result").html(data); 
       }); 
    };
    

    Disclaimer: I m not a PHP developer so please treat teh code below as pseudo-code.

    PHP Part:

    if ($_POST['action'] == "showpost") {    
    var pageSize = 5;  
    var pageNumber = $_POST['pageNumber'];    
    var from = (pageNumber - 1) * pageSize;   
    var to = pageNumber * pageSize;  
    $db->query( "SELECT title FROM post LIMIT " + from + "," + pageSize);   
    while ( $row = $db->get_row()) {    echo $row['title']."<br>";   }     
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 streamingtool
  • ¥15 MATLAB图像问题
  • ¥20 树莓派5做人脸情感识别与反馈系统
  • ¥15 selenium 控制 chrome-for-testing 在 Linux 环境下报错 SessionNotCreatedException
  • ¥15 使用pyodbc操作SQL数据库
  • ¥15 MATLAB实现下列
  • ¥30 mininet可视化打不开.mn文件
  • ¥50 C# 全屏打开Edge浏览器
  • ¥80 WEBPACK性能优化
  • ¥30 python拟合回归分析