這幾天在研究 jQuery,順手做了一個圖片瀏覽的小練習:上方是縮圖列表與前後頁按鈕,點縮圖在下方顯示大圖,翻頁則重新向後端要一批資料。資料格式用 JSON,後端是一個一般處理程序(.ashx)。
效果圖:

1. 建一個 viewer.htm 作為檢視頁,版面分三塊:上方縮圖列與左右按鈕、下方大圖、底部頁碼資訊。
2. 建一個 viewServer.ashx 一般處理程序,負責回應兩種請求:取總數、取指定區間的資料。
3. 資料庫裡存圖片路徑與描述。每張縮圖對應一張大圖,點擊縮圖時才載入大圖。
4. 前端以 AJAX + JSON 溝通,把起始與結束編號送到後端,後端查表後序列化回傳。
<!DOCTYPE html>
<html>
<head>
<title>我的照片</title>
<style type="text/css">
#top { width:1000px; height:100px; margin:auto; }
#leftBtn { width:18px; 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:0 5px 0 10px; }
#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(){
var PAGE_SIZE = 9;
loadPhoto(1, PAGE_SIZE); // 初次載入 1–9
$("#count").text("1");
// 上一頁
$("#leftBtn").click(function(){
var firstIndex = parseInt($("#smallTr :first-child img").attr("id"), 10);
if (firstIndex <= 1) { return; } // 已在第一頁
var startId = firstIndex - PAGE_SIZE;
$("#count").text(startId);
loadPhoto(startId, startId + PAGE_SIZE - 1);
});
// 下一頁
$("#rightBtn").click(function(){
var sum = parseInt($("#sum").text(), 10);
var lastIndex = parseInt($("#smallTr :last-child img").attr("id"), 10);
if (lastIndex >= sum) { return; } // 已在最後一頁
var startId = lastIndex + 1;
$("#count").text(startId);
loadPhoto(startId, startId + PAGE_SIZE - 1);
});
});
// 取得圖片總數
function getCountPhoto(){
$.post("viewServer.ashx", { action: "countPhoto" }, function(data, status){
if (status != "success") { alert("圖片總數載入失敗!"); return; }
$("#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("縮圖載入失敗!"); return; }
getCountPhoto();
$("#smallTr").empty();
var photos = $.parseJSON(data); // 字串轉 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);
});
// 為新的縮圖綁定事件
$("#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 id="loading" style="display:none">載入中.....</span><br />
<img id="tmpimg" src="" style="height:600px; width:800px;" />
</div>
<br />
<div id="bottom">
共 <span id="sum"><strong>0</strong></span> 張,目前第
<span id="count"><strong>0</strong></span> 張
</div>
</form>
</body>
</html>
<%@ WebHandler Language="C#" Class="viewServer" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class viewServer : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json; charset=utf-8";
string action = context.Request["action"].ToString();
if (action == "countPhoto")
{
string sql = "select count(*) from T_SmallPhotos";
DataTable dt = sqlHelper.GetTable(sql);
context.Response.Write(Convert.ToInt32(dt.Rows[0][0]).ToString());
}
else if (action == "getData")
{
string startId = context.Request["startId"].ToString();
string endId = context.Request["endId"].ToString();
// 使用开窗函数 rownum 做分页
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";
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])));
}
var jss = new JavaScriptSerializer();
context.Response.Write(jss.Serialize(list));
}
}
public bool IsReusable { get { return false; } }
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 是自己寫的資料存取類別,這裡從略。
一開始我想在頁面載入時同時取得總數與圖片列表:
$(function(){
loadPhoto(1, 9);
getCountPhoto();
});
結果頁面內容總是怪怪的。除錯後才發現:兩個 AJAX 請求是並行發出的,不會等第一個做完才做第二個。而 getCountPhoto() 實際上是被寫在 loadPhoto 的回呼裡呼叫的,等於同一批資料被撈了兩次,順序還不固定。
三種解法:
一、合併成一個請求。最乾淨的做法。讓後端一次回傳 { total: 128, photos: [...] },前端就不必協調兩個非同步流程。
二、用 jQuery.when() 等待兩者都完成。若無合併後端,這是最直觀的寫法:
$.when(
$.post("viewServer.ashx", { action: "countPhoto" }),
$.post("viewServer.ashx", { startId: 1, endId: 9, action: "getData" })
).done(function (countRes, dataRes) {
$("#sum").text(countRes[0]);
renderPhotos($.parseJSON(dataRes[0]));
});
三、把依賴關係寫出來。總數要在圖片渲染之後才更新,那就明確放在 loadPhoto 的成功回呼裡——這正是原範例的做法,只是它同時又在外部呼叫了一次,才會出問題。
用 $.parseJSON 之前先確認 dataType。在 $.post 的第四個參數加上 "json",jQuery 就會自動解析,回呼收到的已經是物件,不必手動轉。
縮圖與大圖應該分開。目前用同一張圖當縮圖,載入九張就是九份完整圖片。實務上後端應該多提供一個縮圖欄位。
事件綁定時機。範例在 AJAX 回呼外綁定 $("#smallTr img"),但那時元素還不存在。改用事件代理 $("#smallTr").on("click", "img", fn) 可以一次解決,也不必每次翻頁重新綁。
SQL 請用參數化查詢。範例已正確使用 SqlParameter,這點值得保持——千萬不要為了方便就把 startId 直接拼進字串。
缺少 alt 屬性。圖片必須有 alt,資料庫裡既然已經存了 imageAlt,就該用在 img 上,這對螢幕閱讀器使用者是必要的。
載入失敗要處理。photos 若為空陣列,photos[0].ImageUrl 會直接丟出例外。記得先判斷長度。