利用AjAX動態變換過濾條件

來源:互聯網
上載者:User
ajax|動態|條件

在我的一個java項目中,需要在資料列表的上面添加過濾功能,可且根據使用者選擇的過濾條件,來產生不同過濾指令碼:
//**********************以下是表格的第一行指令碼***************************//
   <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>
    <TD align="center" width="18%"><A class="TextUrl9" href="javascript:doFilter();">
     <IMG src="http://www.pushad.com/images/image/chaxun.gif" align="absMiddle" border="0">開始過濾</A>
       <A class="TextUrl9" href="javascript:doAll();"><IMG
     src="http://www.pushad.com/images/image/cx.gif" align="absMiddle" border="0">全部</A>
    </TD>
  </TR>
//*********************************以下是JavaScript指令碼******************************************************//
 /*擷取用戶端XMLHttpRequest請求對象*/
 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>";
    static final String DATE   ="<input id=\"@name\" type=\"text\" name=\"@name\" value='@value' \n"
                                +"         class=\"TextBox\" readonly=\"readonly\" style=\"width:100px;\"/> \n"
                         +"         <IMG style=\"CURSOR: hand\" onclick=\"showtime(@name)\"\n"
                                +"         alt=\"選擇日期\" src=\"../images/image/date.gif\" width='16' align='middle'>";
                               
    //doGet和doPost中的源碼
    response.setContentType(CONTENT_TYPE);
    PrintWriter out=response.getWriter();
    String name=request.getParameter("name");
    out.print(PageList.getFilter(name));
       
   /**
     * 得到過濾類型
     * @param name   過濾選擇名稱(包括表名和欄位名)
     * @param isAdd  是否添加ClassID,BindField等資訊
     * @return
     */
    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"))){//固定代碼
                      if(isAdd)
                          return "2_"+rs.getString("ClassID");
                      else
                          return "2";
                  }else if(!isDBNull(rs.getString("BindTable"))){//外部索引鍵關聯
                      if(isAdd)
                          return "3_"+rs.getString("BindTable")
                                 +"_"+rs.getString("BindField")
                                 +"_"+rs.getString("BindShowField");
                      else
                          return "3";
                  }else if(Common.in(NUM,rs.getString("FieldType"))){//數值
                      return "4";
                  }
              }
             }catch(Exception e){}
         }
        }
        return "0";//一般字元串
    }
   
    /**
     * 擷取過濾字串
     * @param name   過濾類型名稱
     * @param value  第一個過濾值
     * @param value1 第二個過濾值(主要針對時間)
     * @return
     */
    public static String getFilter(String name,String value,String value1){
        String type=getFilterType(name,true);
        int flag=0,pos=type.indexOf("_");
        String[] other=type.split("_");
        if(pos>=0){
            flag=Integer.parseInt(type.substring(0,pos));
        }else{
            flag=Integer.parseInt(type);
        }
        return getFilter(flag,other,value,value1);
    }
   
    /**
     * 擷取過濾字串
     * @param type    過濾類型
     * @param other   固定代碼編號等
     * @param value   第一個過濾值
     * @param value1  第二個過濾值(主要針對時間)
     * @return
     */
    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 "";
    }
    /**
     * 得到過濾字串
     * @param name 過濾名稱
     * @return
     */   
    public static String getFilter(String name){
        return getFilter(name,"","");
    }
   
    /**
     * 檢查是否為空白
     * @param obj 要檢查的對象
     * @return
     */
    public static boolean isNull(Object obj){
        if(obj==null || obj.toString().equals(""))
            return true;
        else
            return false;
    }
   
    /**
     * 判斷是否為空白,包括空欄位
     * @param obj 要判斷的對象
     * @return
     */
    public static boolean isDBNull(Object obj){
        if(isNull(obj) || obj.toString().trim().toLowerCase().equals("null"))
            return true;
        else
            return false;
    }
//*****************************************************************************************//
原理:根據選擇不同的過濾條件,擷取條件中的表名和欄位名,利用Ajax根據表名和欄位名在資料字典中擷取它的類型:
(1)如果是日期型:返回日期範圍選擇
(2)如果是固定代碼:返回一個下拉式清單,並初始化固定代碼
(3)如果是外部索引鍵關聯:則讀出所有的外鍵所對應的名稱
(4)否則返回一個文本輸入框
這樣選擇不同的過濾條件(或者說過濾欄位),產生不同的過濾效果,而且是非同步,下面顯示的資料列表不用重新整理,在這個項目中獲得了較好的使用者體驗。

以下是截圖:



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.