這件事要從頭說起才讲得清楚。
後台有個欄位叫 keywords,裡頭存著類似這樣的一串值:
efmis://|efmfj|username|2200|0||2014|https://10.20.1.54:7001/cssServerportal222012/|||||02
這串東西的含義先不管,相信很多人都遇過更複雜的設定字串。前台要顯示時寫 ${tag_bean.keywords} 就好,後台怎麼設,畫面就原封不動怎麼顯示。第一個麻煩馬上出現:username 那個位置必須換成「當前登入者的帳號」,也就是說它得是動態的。
那直接在後台寫成 efmis://|efmfj|${username}|2200|0||2014|https://... 呢?行不通。它會被當成純文字原樣印出來,EL 運算式根本不會被解析。既然不能靠後台搞定,就只能在這個字串被使用前先處理一輪。
這串值最終是要傳給某個 JavaScript 方法的參數,畫面上大致長這樣:
複製代碼 代碼如下:
<li [#if c.keywords?exists] keywords="${c.keywords}"
[/#if] path="${c.path}" onclick="clickClient(this.path,this.keywords);">
<a href="javascript:void(0)" style="cursor: pointer;"><span>${c.name}</span>
</a>
</li>
clickClient 不是真正要做事的方法,它只是個過渡層,負責把字串整理乾淨:
複製代碼 代碼如下:
clickClient = function(path,keywords){
//解析分解keywords開始
keywords = keywords.replace("username","${user.username}");
var suffIndex=keywords.indexOf("http");
var prefix = keywords.substr(0,suffIndex-1);
var suffix = keywords.substr(suffIndex-1);
var preIndex=prefix.lastIndexOf("|")+1;
var year = prefix.substr(preIndex);
prefix = prefix.substr(0,preIndex);
//解析分解keywords結束
//合並url
keywords = prefix+$("#year").val()+suffix;
clientInvoke(path,keywords);
}
關鍵在最後一行替換:把字串裡的 username 換成 ${user.username}。因為這段程式碼本身就在 JSP 頁面中執行,即使寫在 JavaScript 裡,EL 運算式一樣會被動態解析——這樣就達成了「帶入當前登入者帳號」的目標。
接著需求升級:2014 這個年度也要能動態變更。做法是把它從字串裡切出來,拆成三段:
前綴:efmis://|efmfj|username|2200|0||
年度:2014
後綴:|https://10.20.1.54:7001/cssServerportal222012/|||||02
年度放進一個下拉選單,觸發 clickClient 時即時從目前的 option 取值,再跟前後綴拼回去,靈活度就有了。
複製代碼 代碼如下:
年度切換 <select id="year" onclick="switchYear(this.value);"> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014" selected="selected">2014</option> <option value="2015">2015</option> </select>
新問題來了:使用者把年度從 2014 切到 2013,一按重新整理又跳回 2014。刷新之後所有變數都重新初始化,全域變數這條路走不通。那什麼東西不會因為換頁而消失、又方便我們讀寫?就是 Cookie。
Cookie 是存在瀏覽器端的資源,隨存隨取,「記住密碼」那類功能全靠它。做法很直觀:頁面載入時先檢查 Cookie 裡有沒有年度,有就寫回下拉選單,沒有就把選單目前的值存進去。
複製代碼 代碼如下:
$(document).ready(function(){
if(getCookie("Year")==null){//不存在該cookie,放進去
setCookie("Year",$("#year").val());
}else{
//已經存在該cookie,則從中取出
$("#year").val(getCookie("Year"));
}
});
//設置cookie
function setCookie(name,value)
{
//var Days = 30;
//var exp = new Date();
//exp.setTime(exp.getTime() + 365*24*60*60*1000);
document.cookie = name + "="+ escape (value);
// + ";expires=" + exp.toGMTString();
}
//讀取cookies
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg)) return unescape(arr[2]);
else return null;
}
切換年度時,Cookie 也得跟著更新:
複製代碼 代碼如下:
switchYear=function(year){
setCookie("Year",year);
}
最後一個耐人尋味的細節:需求方要求「每次重新登入,年度一定要回到 2014,不能停在上次切換的值」。既然這樣,就乾脆不要設定過期時間,讓 Cookie 在瀏覽器關閉後自動消失,下次開啟自然拿不到舊值。反過來,如果希望瀏覽器長期記住選擇,只要把 setCookie 裡那幾行註解掉的過期設定放回來即可,有興趣的可以試著調整天數。