前言:本範例的功能是——前端透過 jQuery Ajax 呼叫一般處理程序(.ashx Handler)取得表格所需的資料,後端把資料轉成 JSON 格式回傳,前端拿到後迴圈組出表格的每一列,最後附加到 table 元素上。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DialogAjax.aspx.cs" Inherits="JQueryTest_DialogAjax" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="../JQueryUi/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css" /> <script src="../JQueryUi/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="../JQueryUi/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script> <style type="text/css"> #divTb { width:800px; border:1px solid #aaa; margin:0 auto; } .even{background:#CCCCCC;} .odd{background:#FFFFFF;} </style> <script type="text/javascript"> function getModuleInfo() { $.ajax({ type: "GET", dataType: "json", url: "../Handler/TestHandler.ashx?Method=GetModuleInfo", success: function(json) { var typeData = json.Module; $.each(typeData, function(i, n) { var tbBody = "" var trColor; if (i % 2 == 0) { trColor = "even"; } else { trColor = "odd"; } tbBody += "<tr class='" + trColor + "'><td>" + n.ModuleNum + "</td>" + "<td>" + n.ModuleName + "</td>" + "<td>" + n.ModuleDes + "</td></tr>"; $("#myTb").append(tbBody); }); }, error: function(json) { alert("加載失敗"); } }); } $(function() { getModuleInfo(); }); </script> </head> <body> <form id="form1" runat="server"> <div id="divTb"> <table id="myTb" style=" width:100%"> </table> </div> </form> </body> </html>
<%@ WebHandler Language="C#" Class="TestHandler" %> using System; using System.Web; using System.Collections.Generic; using System.Text; using DataDAL; using DataEnity; public class TestHandler : IHttpHandler { HttpRequest Request; HttpResponse Response; public void ProcessRequest (HttpContext context) { //不讓瀏覽器緩存 context.Response.Buffer = true; context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); context.Response.AddHeader("pragma", "no-cache"); context.Response.AddHeader("cache-control", ""); context.Response.CacheControl = "no-cache"; context.Response.ContentType = "text/plain"; Request = context.Request; Response = context.Response; string method = Request["Method"].ToString(); System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(method); methodInfo.Invoke(this, null); } public void GetModuleInfo() { StringBuilder sb = new StringBuilder(); string jsonData = string.Empty; List<Module> lsModule = ModuleDAL.GetModuleList(); sb.Append("{\"Module\":["); for (int i = 0; i < lsModule.Count; i++) { jsonData = "{\"ModuleNum\":" + "\"" + lsModule[i].ModuleNum + "\"" + ",\"ModuleName\":" + "\"" + lsModule[i].ModuleName + "\"" + ",\"ModuleDes\":" + "\"" + lsModule[i].ModuleDes + "\"" + "},"; sb.Append(jsonData); } if (lsModule.Count > 0) sb = sb.Remove(sb.Length - 1, 1); sb.Append("]}"); Response.Write(sb); } public bool IsReusable { get { return false; } } }
程式碼確實很簡短,但正式專案裡有幾處建議調整:
1. 別用反射分派方法。用 GetType().GetMethod(Request["Method"]) 決定要呼叫哪個函式,等於讓任何能連到這個端點的人,只要改一下 query string 就能呼叫這個類別上的任何 public 方法。改用 switch 或路由表明確列出可呼叫的方法,這是最起碼的把關。
2. 手工串 JSON 很危險。範例用 StringBuilder 拼字串,只要某個欄位裡出現雙引號、換行或反斜線,整份 JSON 就會壞掉;若資料含有使用者輸入,這更是現成的注入入口。請直接用 JsonConvert.SerializeObject() 或 System.Web.Script.Serialization.JavaScriptSerializer。
3. ContentType 應該是 application/json。設成 text/plain 雖然前端指定了 dataType: "json" 時還能勉強運作,但這是不正確的表達方式,會讓快取、除錯與第三方工具誤判。
4. 表格組裝可以更快。目前是每圈迴圈都呼叫一次 $("#myTb").append(),資料量大時會反覆觸發 DOM 更新。把 tbBody 累積完再一次 append,或在迴圈外先建立好完整的 HTML 字串再插入,效能會好很多。