在一個 Java 專案中,資料列表上方往往需要一組過濾功能,能依據使用者選擇的欄位,動態產生對應的過濾輸入元件。若每切換一次就刷新整頁,體驗會大打折扣。本文示範如何借助 AJAX,讓過濾條件的介面在不重整列表的前提下即時變化。
表格首列提供一個下拉選單,讓使用者挑選要過濾的欄位,例如 Bug 標題、安裝用戶、安裝系統、提交時間或完成時間;右側的 filter 儲存格則放著目前對應的過濾輸入元件。
<TD align="center" width="15%" height="25">選擇查詢條件:</TD>
<TD align="left" width="30%"><select name="FilterName" id="FilterName" style="width:100%">
<option value=""></option>
<option value='BugInfo_Title'<%=BugInfoList.getSelected("BugInfo_Title")%>>Bug標題</option>
<option value='BugInfo_BugUser'<%=BugInfoList.getSelected("BugInfo_BugUser")%>>安裝用戶</option>
<option value='BugInfo_BugSystem'<%=BugInfoList.getSelected("BugInfo_BugSystem")%>>安裝系統</option>
<option value='BugInfo_BugTime'<%=BugInfoList.getSelected("BugInfo_BugTime")%>>提交時間</option>
<option value='BugInfo_DoneTime'<%=BugInfoList.getSelected("BugInfo_DoneTime")%>>完成時間</option>
</select></TD>
<TD align="left" width="37%" id="filter"><%=BugInfoList.getFilterHtml()%></TD>
getRequest 負責建立跨瀏覽器的 XMLHttpRequest;changeFilter 依使用者所選欄位發出請求;updateFilter 則在回應抵達後,把伺服器傳回的 HTML 寫入 filter 元素。值得留意的是,使用完畢後必須清空 request,避免記憶體殘留。
function getRequest(){
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request) alert("錯誤初始化XMLHttpRequest對象!");
return request;
}
var request = getRequest();
// 改變過濾條件
function changeFilter() {
if(request==null) request=getRequest();
var name = FrmBugInfo.FilterName.value;
var url = "../AJaxFilter?name="+name;
request.onreadystatechange = updateFilter;
request.open("GET", url, true);
request.send(null);
}
// 更新過濾條件
function updateFilter(){
if (request.readyState == 4) {
if (request.status == 200) {
var text = request.responseText;
document.getElementById("filter").innerHtml = text;
} else {
alert("狀態是:" + request.status);
}
delete request['onreadystatechange'];
request = null; // 必須清空
}
}
核心是 AJaxFilter 這個 servlet。它會解析傳入的欄位名稱(含表名與欄位名),到資料字典查詢其型別,再據此回傳不同的輸入元件:日期型回傳日期區間選擇、固定代碼回傳下拉清單、外鍵關聯讀出對應名稱,其餘則回傳一般文字輸入框。
static final String[] TIME={"smalldatetime","datetime","timestamp"};
static final String[] NUM ={"tinyint","smallint","int","bigint","decimal","numeric",
"float","real","smallmoney","money","binary"};
static final String SQL ="select * from DataDict where TableName='%s' and FIEldName='%s'";
static final String DEFAULT="<input type='text' name='FilterValue' id='FilterValue' value='@value' style='width:100%'></input>";
// doGet 與 doPost 中的核心片段
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
out.print(PageList.getFilter(name));
// 取得過濾類型:0 字串、1 時間、2 固定代碼、3 外鍵、4 數值
public static String getFilterType(String name, boolean isAdd){
if(name!=null){
int index = name.indexOf("_");
if(index>=0){
String[] str = new String[2];
str[0] = name.substring(0,index);
str[1] = name.substring(index+1);
ResultSet rs = DBAccess.getInstance().OpenCommand(Common.Format(SQL,str));
try{
if(rs.next()){
if(Common.in(TIME,rs.getString("FIEldType"))){
return "1";
}else if(!isDBNull(rs.getString("ClassID"))){
return isAdd ? "2_"+rs.getString("ClassID") : "2";
}else if(!isDBNull(rs.getString("BindTable"))){
return isAdd ? "3_"+rs.getString("BindTable")+"_"+rs.getString("BindFIEld")+"_"+rs.getString("BindShowFIEld") : "3";
}else if(Common.in(NUM,rs.getString("FIEldType"))){
return "4";
}
}
}catch(Exception e){}
}
}
return "0"; // 一般字串
}
// 依型別產生過濾字串
public static String getFilter(int type, String[] other, String value, String value1){
if(value==null) value="";
if(value1==null) value1="";
switch(type){
case 0: return DEFAULT.replaceAll("@value",value); // 字串
case 1: return ("從:"+DATE.replaceAll("@name","FromDate").replaceAll("@value",value)
+" 到:"+DATE.replaceAll("@name","ToDate").replaceAll("@value",value1)); // 時間
case 2: if(other.length==2)
return Html.getInstance().GetList("Exec P_GetBaseCode '"+other[1]+"'",true,true,"FilterValue","100%",value); // 固定代碼
case 3: if(other.length==4)
return Html.getInstance().GetList("select distinct "+other[2]+","+other[3]+" from "+other[1],true,true,"FilterValue","100%",value); // 外鍵關聯
case 4: return DEFAULT.replaceAll("@value",value); // 數值
}
return "";
}
整體流程是:使用者切換過濾欄位 → 前端解析出表名與欄位名 → 透過 AJAX 到資料字典查型別 → 伺服器回傳對應的輸入元件 → 前端局部更新。因為全程非同步,下方資料列表完全不用刷新,使用者操作不會中斷,體驗相當流暢。
以下為幾個畫面示意:


