jquery动态加载图片数据练习代码

  这几天研究jquery,感受到了该库的强大,而且找到本不错的书 <<锋利的jquery>>

  这里我只是随便做了下,上面是照片列表和两个按钮,单击小图片下面显示大图片,当点击按钮时可以查看下一页,上一页的图片。

  思路:

  1、首先建一个照片查看页面viewer.htm,简单布局,上面是小图片和两个按钮,下面是大图片。

  2、建一个一般处理程序viewServer.ashx,用来处理照片查看页面的请求。

  3、然后当然要用到数据库啦,包括图片的路径,描述等信息。每张小图片路径应该对应一张大图片,单击小图片时候再加载,这里我没做小图片所以都用大图片加载了。

  4、数据传输使用json,建立一个加载图片的函数,当页面加载或者单击left、right按钮的时候,通过ajax加载图片,将请求图片的开始编号、结束编号传递到后台页面,

    后台页面收到请求信息后,在数据库中查找所需图片信息。

  效果如图:

jquery动态加载图片数据练习代码

  实现代码:

  viewer.htm

  

复制代码 代码如下:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>

  <title>我的照片</title>

  <style type="text/css">

  #top{width:1000px;height:100px;margin:auto;}

  #leftBtn{width: 18px; text-align: left;height: 100px; float:left; background-image: url(images/images/left.jpg);}

  #rightBtn{width: 18px; height: 100px; float:right;background-image: url(images/images/right.jpg);}

  #smallPhoto{ text-align: center; float:left;margin-left:10px;margin-right:5px; }

  #bigPhoto{width:1000px;height:600px;text-align:center;margin:auto;}

  .photo{width:100px; height:100px;cursor:pointer;}

  #bottom{width:1000px;height:50px;margin:auto;}

  </style>

  <script src="../js/jquery-1.4.2.js" type="text/javascript"></script>

  <script type="text/javascript">

  $(function(){

  loadPhoto(1,9);//页面加载函数,每次显示9张图片,加载时候显示1-9

  $("#count").text("1");

  $("#leftBtn").click(function(){

  var firstIndex=parseInt($("#smallTr :first-child image").attr("id"),10);

  if(firstIndex<=1){ //如果已经到第一页了

  return;

  }

  else{

  var startId=firstIndex-9;

  var endId=startId+8;

  $("#count").text(startId);

  loadPhoto(startId,endId);

  }

  });

  $("#rightBtn").click(function(){

  var sum=$("#sum").text();

  var lastIndex=parseInt($("#smallTr :last-child image").attr("id"),10);

  if(lastIndex>=parseInt(sum,10)){ //如果已经到最后一页了

  return;

  }

  else{

  var startId=lastIndex+1;

  var endId=startId+8;

  $("#count").text(startId);

  loadPhoto(startId,endId);

  }

  });

  });

  //获取图片总数

  function getCountPhoto(){

  $.post("viewServer.ashx",{"action":"countPhoto"},function(data,status){

  if(status!="success"){

  alert("图片总数加载失败!");

  }

  else{

  $("#sum").text(data);

  }

  });

  };

  //加载图片的公共函数,索引从startid到endId

  function loadPhoto(startId,endId){

  $.post("viewServer.ashx",{"startId":startId,"endId":endId,"action":"getData"},function(data,status){ //告诉后台要哪几张图片

  if(status!="success"){

  alert("小图片加载失败!");

  }

  else{

  getCountPhoto(); //获取图片总数

  $("#smallTr").empty();

  var photos=$.parseJSON(data); //使用json传递数据,json用着就是爽啊

  for(var i=0;i<photos.length;i++){

  var photo=photos[i];

  var td=$("<td ><img id='"+photo.Rownum+"' class='photo' src='images/"+photo.ImageUrl+"'/></td>");

  $("#smallTr").append(td);

  }

  $("#tmpimg").attr("src","images/"+photos[0].ImageUrl);

  }

  //为每个小图片设置mouseover和click事件

  $("#smallTr img").mouseenter(function(){

  $(this).attr("cursor","pointer");

  })

  .click(function(){

  $("#count").text($(this).attr("id"));

  $("#tmpimg").attr("src",$(this).attr("src"));

  });

  });

  };

  //如果图片加载过慢,提示加载中。。。。

  $("#loading").ajaxStart(function(){

  $(this).show();

  })

  .ajaxStop(function(){

  $(this).hide();

  });

  </script>

  </head>

  <body style="text-align: center;">

  <form id="form1" runat="server">

  <div id="top" style="text-align: center">

  <input id="leftBtn" type="button" />

  <div id="smallPhoto">

  <table>

  <tr id="smallTr">

  </tr>

  </table>

  </div>

  <input id="rightBtn" type="button" />

  </div>

  <div id="bigPhoto">

  <span style="display:none;" id="loading">加载中.....</span> <br /> <img id="tmpimg" src="" style="position: relative; height: 600px; width: 800px;"/>

  </div>

  <br />

  <div id="bottom">

  共<span id="sum" style="visibility: visible;"><strong>0</strong></span>张, 当前第<span id="count" style="visibility:visible;"><strong>0</strong></span>张

  </div>

  </form>

  </body>

  </html>

  viewserver.ashx:

  

复制代码 代码如下:

  <%@ WebHandler Language="C#" Class="viewServer" %>

  using System;

  using System.Web;

  using System.Data.SqlClient;

  using System.Data;

  using System.Collections.Generic;

  public class viewServer : IHttpHandler

  {

  public void ProcessRequest(HttpContext context)

  {

  context.Response.ContentType = "text/plain";

  string action = context.Request["action"].ToString();

  if (action == "countPhoto") //统计共有多少图片

  {

  string sql = "select count(*) from T_SmallPhotos";

  DataTable dt = sqlHelper.GetTable(sql);

  int count = Convert.ToInt32(dt.Rows[0][0]);

  context.Response.Write(count.ToString());

  }

  else if (action == "getData") //请求图片数据

  {

  string startId = context.Request["startId"].ToString();

  string endId = context.Request["endId"].ToString();

  //string sqlStr = string sqlStr = "SELECT * FROM (SELECT id, [imageName], [imageUrl], [imageAlt], [notes], Row_Number() OVER (ORDER BY id) rownum FROM T_SmallPhotos) t WHERE t .rownum >= 1 AND t .rownum <=5"

  //这个查询语句有点小复杂,使用了开窗函数

  string sqlStr = "SELECT * FROM (SELECT id, [imageName], [imageUrl], [imageAlt], [notes], Row_Number() OVER (ORDER BY id) rownum FROM T_SmallPhotos) t WHERE t .rownum >= @startId AND t .rownum <= @endId";

  //string sqlStr = "SELECT [id], [imageName], [imageUrl], [imageAlt], [notes] FROM [T_SmallPhotos] where id>1 and id<10";

  SqlParameter[] param = new SqlParameter[] {new SqlParameter("@startId",startId),

  new SqlParameter("@endId",endId)};

  DataTable dt = sqlHelper.GetTable(sqlStr, param);

  List<Photo> list = new List<Photo>();

  for (int i = 0; i < dt.Rows.Count; i++)

  {

  list.Add(new Photo(Convert.ToInt32(dt.Rows[i][0]), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), Convert.ToInt32(dt.Rows[i][5])));

  }

  System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();//将数据序列化为json数据

  context.Response.Write(jss.Serialize(list));

  }

  }

  public bool IsReusable

  {

  get

  {

  return false;

  }

  }

  //封装一个照片类,然后使用json传递

  public class Photo

  {

  public Photo(int i, string name, string url, string alt, string notes, int rownum)

  {

  id = i;

  imageName = name;

  imageUrl = url;

  imageAlt = alt;

  this.notes = notes;

  this.rownum = rownum;

  }

  private int id; //图片编号

  public int Id

  {

  get { return id; }

  set { id = value; }

  }

  private string imageName;//图片名称

  public string ImageName

  {

  get { return imageName; }

  set { imageName = value; }

  }

  private string imageUrl; //图片路径

  public string ImageUrl

  {

  get { return imageUrl; }

  set { imageUrl = value; }

  }

  private string imageAlt; //图片描述

  public string ImageAlt

  {

  get { return imageAlt; }

  set { imageAlt = value; }

  }

  private string notes;

  public string Notes

  {

  get { return notes; }

  set { notes = value; }

  }

  private int rownum;

  public int Rownum

  {

  get { return rownum; }

  set { rownum = value; }

  }

  }

  }

  其中sqlHelper是我自定义的数据库访问类,比较简单就不贴出来了。

  在实现过程中遇到一个ajax方面的问题,现在还是没搞太明白:

  我的js代码中有两个请求函数,一个是获取图片总数getCountPhoto(),一个是加载图片的公共函数loadPhoto(startId,endId),我想在页面加载的时候同时调用这两个函数,分别显示出页码信息和具体图片列表,

  

复制代码 代码如下:

  $(function(){

  loadPhoto(1,9);

    getCountPhoto();

  }

  这样的话发现页面内容总是错误,经过调试发现原来两个ajax请求是交叉执行,并不是一个执行完成执行另一个的。

  这就是前几天做的了。