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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog