这几天研究jquery,感受到了该库的强大,而且找到本不错的书 <<锋利的jquery>>
这里我只是随便做了下,上面是照片列表和两个按钮,单击小图片下面显示大图片,当点击按钮时可以查看下一页,上一页的图片。
思路:
1、首先建一个照片查看页面viewer.htm,简单布局,上面是小图片和两个按钮,下面是大图片。
2、建一个一般处理程序viewServer.ashx,用来处理照片查看页面的请求。
3、然后当然要用到数据库啦,包括图片的路径,描述等信息。每张小图片路径应该对应一张大图片,单击小图片时候再加载,这里我没做小图片所以都用大图片加载了。
4、数据传输使用json,建立一个加载图片的函数,当页面加载或者单击left、right按钮的时候,通过ajax加载图片,将请求图片的开始编号、结束编号传递到后台页面,
后台页面收到请求信息后,在数据库中查找所需图片信息。
效果如图:
实现代码:
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; 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;
publicclass viewServer : IHttpHandler
{
publicvoid 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());
}
elseif (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));
}
}
publicbool IsReusable
{
get
{
returnfalse;
}
}
//封装一个照片类,然后使用json传递
publicclass 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;
}
privateint id; //图片编号
publicint Id
{
get { return id; }
set { id = value; }
}
privatestring imageName;//图片名称
publicstring ImageName
{
get { return imageName; }
set { imageName = value; }
}
privatestring imageUrl; //图片路径
publicstring ImageUrl
{
get { return imageUrl; }
set { imageUrl = value; }
}
privatestring imageAlt; //图片描述
publicstring ImageAlt
{
get { return imageAlt; }
set { imageAlt = value; }
}
privatestring notes;
publicstring Notes
{
get { return notes; }
set { notes = value; }
}
privateint rownum;
publicint Rownum
{
get { return rownum; }
set { rownum = value; }
}
}
}
其中sqlHelper是我自定义的数据库访问类,如下
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.DirectoryServices;
using System.Data.SqlClient;
using System.IO;
///<summary>
/// sqlHelper 的摘要说明
///</summary>
publicclass sqlHelper
{
privatestaticstring _dbPath = Path.GetFullPath(@"..\App_Data\Photos.mdf");
//private static string _conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + _dbPath + ";Integrated Security=True";
//private static string _conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Photos.mdf;Integrated Security=True;User Instance=True";
privatestaticstring _conStr =@"Data Source=.\SQLEXPRESS;Initial Catalog=Photos;Integrated Security=True";
//private static string _conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + _dbPath + ";user ID=sa;Pwd=123"; //sqlserver认证方式
privatestatic SqlConnection _sqlCon =null;
public sqlHelper()
{
}
///<summary>
/// 创建数据库连接,
/// 若为创建数据库连接,先创建数据库连接并打开。
/// 若数据库连接状态为关闭或者中断,先将其关闭然后打开
///</summary>
privatestaticvoid CreateConnection()
{
if (_sqlCon ==null)
{
_sqlCon =new SqlConnection(_conStr);
_sqlCon.Open();
}
elseif (_sqlCon.State == ConnectionState.Closed || _sqlCon.State == ConnectionState.Broken)
{
_sqlCon.Close();
_sqlCon.Open();
}
}
///<summary>
/// 关闭数据库连接
///</summary>
publicstaticvoid CloseConnection()
{
_sqlCon.Close();
}
///<summary>
/// 获取数据库连接
///</summary>
///<returns></returns>
publicstatic SqlConnection GetConnection()
{
return _sqlCon;
}
///<summary>
/// 执行增、删、改操作,返回影响行数,若失败返回-1
///</summary>
///<param name="sqlStr"></param>
///<returns></returns>
publicstaticint ExeNoQuery(string sqlStr)
{
int result =0;
try
{
CreateConnection();
SqlCommand sqlCom =new SqlCommand(sqlStr, _sqlCon);
result = sqlCom.ExecuteNonQuery();
_sqlCon.Close();
return result;
}
catch
{
return-1;
}
}
///<summary>
/// 执行增、删、改操作,返回影响行数,若失败返回-1
///</summary>
///<param name="sqlStr"></param>
///<returns></returns>
publicstaticint ExeNoQuery(string sqlStr, params SqlParameter[] param)
{
int result =0;
try
{
CreateConnection();
SqlCommand sqlCom =new SqlCommand(sqlStr, _sqlCon);
foreach (SqlParameter par in param)
{
sqlCom.Parameters.Add(par);
}
result = sqlCom.ExecuteNonQuery();
_sqlCon.Close();
return result;
}
catch
{
return-1;
}
}
///<summary>
/// 执行查询操作,返回数据表
///</summary>
///<param name="sqlStr"></param>
///<returns></returns>
publicstatic DataTable GetTable(string sqlStr)
{
try
{
CreateConnection();
SqlDataAdapter sda =new SqlDataAdapter(sqlStr, _sqlCon);
System.Data.DataSet ds =new DataSet();
sda.Fill(ds);
_sqlCon.Close();
return ds.Tables[0];
}
catch
{
returnnull;
}
}
///<summary>
/// 执行查询操作,返回数据表
///</summary>
///<param name="sqlStr"></param>
///<returns></returns>
publicstatic DataTable GetTable(string sqlStr, params SqlParameter[] param)
{
try
{
CreateConnection();
SqlDataAdapter sda =new SqlDataAdapter(sqlStr, _sqlCon);
foreach (SqlParameter par in param)
{
sda.SelectCommand.Parameters.Add(par);
}
DataSet ds =new DataSet();
sda.Fill(ds);
_sqlCon.Close();
return ds.Tables[0];
}
catch
{
returnnull;
}
}
}
在实现过程中遇到一个ajax方面的问题,现在还是没搞太明白:
我的js代码中有两个请求函数,一个是获取图片总数getCountPhoto(),一个是加载图片的公共函数loadPhoto(startId,endId),我想在页面加载的时候同时调用这两个函数,分别显示出页码信息和具体图片列表,
$(function(){
loadPhoto(1,9);
getCountPhoto();
}
这样的话发现页面内容总是错误,经过调试发现原来两个ajax请求是交叉执行,并不是一个执行完成执行另一个的。
这就是前几天做的了。