每個專案裡都在重複寫一樣的 $.ajax 設定,是個該被消滅的樣板。這裡分三步,把 jQuery 的 Ajax 包成一個通用類,程式碼都附註解,照著做就能用。
<script type="text/javascript" src="<%=path%>/resources/js/jquery.min.js"></script>
這份程式碼已測試可用,可以直接複製調用:
/***************************************************************** jQuery Ajax封裝通用類 (linjq) *****************************************************************/ $(function(){ /** * ajax封裝 * url 發送請求的地址 * data 發送到服務器的數據,數組存儲,如:{"date": new Date().getTime(), "state": 1} * async 默認值: true。默認設置下,所有請求均為異步請求。如果需要發送同步請求,請將此選項設置為 false。 * 注意,同步請求將鎖住浏覽器,用戶其它操作必須等待請求完成才可以執行。 * type 請求方式("POST" 或 "GET"), 默認為 "GET" * dataType 預期服務器返回的數據類型,常用的如:xml、html、json、text * successfn 成功回調函數 * errorfn 失敗回調函數 */ jQuery.ax=function(url, data, async, type, dataType, successfn, errorfn) { async = (async==null || async=="" || typeof(async)=="undefined")? "true" : async; type = (type==null || type=="" || typeof(type)=="undefined")? "post" : type; dataType = (dataType==null || dataType=="" || typeof(dataType)=="undefined")? "json" : dataType; data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: type, async: async, data: data, url: url, dataType: dataType, success: function(d){ successfn(d); }, error: function(e){ errorfn(e); } }); }; /** * ajax封裝 * url 發送請求的地址 * data 發送到服務器的數據,數組存儲,如:{"date": new Date().getTime(), "state": 1} * successfn 成功回調函數 */ jQuery.axs=function(url, data, successfn) { data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: "post", data: data, url: url, dataType: "json", success: function(d){ successfn(d); } }); }; /** * ajax封裝 * url 發送請求的地址 * data 發送到服務器的數據,數組存儲,如:{"date": new Date().getTime(), "state": 1} * dataType 預期服務器返回的數據類型,常用的如:xml、html、json、text * successfn 成功回調函數 * errorfn 失敗回調函數 */ jQuery.axse=function(url, data, successfn, errorfn) { data = (data==null || data=="" || typeof(data)=="undefined")? {"date": new Date().getTime()} : data; $.ajax({ type: "post", data: data, url: url, dataType: "json", success: function(d){ successfn(d); }, error: function(e){ errorfn(e); } }); }; });
這段封裝有三個值得學的設計:
第一,掛在 jQuery 物件上而不是全域函數。用 jQuery.ax = function... 而非 function ax(...),好處是不污染全域命名空間,而且呼叫時寫成 $.ax(...),一眼就知道這是 jQuery 生態的東西。這其實也是 jQuery 插件「靜態方法」的標準寫法。
第二,用預設值消除重複設定。async、type、dataType 都有 fallback,呼叫端只需傳真正在意的參數,其餘交給預設。
第三,data 預設帶一個 timestamp。{"date": new Date().getTime()} 這個技巧是為了防止 GET 請求被瀏覽器快取。每次請求的網址都不同,快取自然失效。這比設 cache: false 更古老但同樣有效。
三個方法分層也很清楚:ax 是全功能版;axs 只處理成功,適合那些「一定會成功、失敗交給全域錯誤處理」的場景;axse 同時處理成功與失敗。
<%@ page language="java" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> <html> <head> <base href="<%=basePath%>"> <title>jQuery Ajax封裝通用類測試</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <jsp:include page="/view/common/js_taglib.jsp"></jsp:include> <script type="text/javascript"> $(function(){ $.ax( getRootPath()+"/test/ajax.html", null, null, null, null, function(data){ alert(data.code); }, function(){ alert("出錯了"); } ); $.axs(getRootPath()+"/test/ajax.html", null, function(data){ alert(data.data); }); $.axse(getRootPath()+"/test/ajax.html", null, function(){ alert("成功了"); }, function(){ alert("出錯了"); }); }); </script> </head> <body> </body> </html>
呼叫端寫起來確實乾淨很多——一個 url、一個回呼,其餘都不用管。
1. 把 async 的預設值改成 boolean。範例中 async 的預設值是字串 "true"。雖然 jQuery 內部會做轉換,但用真正的 true 比較不容易誤解。同步請求本身也應該避免,它會凍結整個 UI。
2. 用物件參數取代長參數列表。七個位置參數的呼叫($.ax(url, null, null, null, null, fn, fn))可讀性很差,很容易傳錯順序而不自知。改成 $.ax({ url: ..., data: ..., success: ... }) 會好得多,這也是前面文章提過的「用物件傳參」的經典應用。
3. 補上 Promise 介面。jQuery 1.5 之後 $.ajax() 本身就回傳 Promise-like 物件,可以 .done().fail().always()。若專案有用 async/await,也能直接 await 它,比回呼巢狀清楚許多。
4. 加上統一的錯誤處理與 loading 狀態。目前每個呼叫點都要自己寫 error 回呼。可以在封裝層集中處理常見的 401、403、500,以及全域的 loading 遮罩,讓呼叫端只關心業務邏輯。
封裝的目的就是讓「每次都要做的事」只做一次。把這幾點補上,這個通用類會更好用。