douyun3022 2013-04-13 05:05
浏览 36
已采纳

PHP / Ajax分页缩略图

My main goal is to create a Pagination with photo thumbnails. I have successfully managed to create my own pagination. But the problem is, I know how to use ajax, I just don't know how to apply ajax to it so that it is more user friendly. Can someone help me out, I have been struggling to find an answer to this problem. Below is my code.

<?php
  require 'php/connect.inc.php';
  $per_page = 3;

  $pages_query = mysql_query("SELECT COUNT('id') FROM my_list");
  $pages = ceil(mysql_result($pages_query, 0) / $per_page);

  $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
  $start = ($page - 1) * $per_page;


  $query = mysql_query("SELECT id, image_small FROM my_list LIMIT $start, $per_page");
  while($mysql_fetch_assoc = mysql_fetch_assoc($query)){
    echo "<img src=".'img/uploads/'.$mysql_fetch_assoc['image_small'].">";
  }

  if ($pages >= 1 && $page <= $pages){
    for ($x=1; $x <= $pages; $x++){
      echo ($x == $page) ? '<strong><a href="?page='.$x.'">'.$x.'</a></strong> ' : '<a href="?page='.$x.'">'.$x.'</a>';
    }
  }
?>
  • 写回答

1条回答 默认 最新

  • dongri1989 2013-04-13 05:40
    关注

    When you build an application json you need two things, first a script that returns an appropriate response and the other a client making requests.

    This is an example of a script that returns json

    <?php
      require 'php/connect.inc.php';
      $per_page = 3;
    
      $pages_query = mysql_query("SELECT COUNT('id') FROM my_list");
      $pages = ceil(mysql_result($pages_query, 0) / $per_page);
    
      $page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
      $start = ($page - 1) * $per_page;
    
    
      $query = mysql_query("SELECT id, image_small FROM my_list LIMIT $start, $per_page");
    
      $results = array();
      while($mysql_fetch_assoc = mysql_fetch_assoc($query)){    
        $results[] = $mysql_fetch_assoc['image_small'];
      }      
    
      header('Content-type: application/json');
    
      echo json_encode(array(
        'thumbs' => $results,
        'pages' => $pages,
        'current_page' => $page,
        'per_page' => $per_page
      ));
    
    ?>
    

    here is a simple client script (javascript using jQuery) for make request

    $.ajax({
      url: "yourscript.php?page=1"
    }).done(function(data) {
      $.each(data.thumbs, function(thumb) {
        // to something
      });
    });
    

    finally recommend you do not use mysql_query and his associates. read php.net/mysql_query is deprecated

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题