DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解 >> 發布一個原創的基於Ajax的通用(組合)查詢(續)
發布一個原創的基於Ajax的通用(組合)查詢(續)
編輯:AJAX詳解     
.AJaxSearchClIEntScript.JS
var tbPanel            = null;        //用於展示組合條件的表控件
var tableName        = null;        //記錄查詢的表
var fIEldsInfo        = null;        //保存從服務端取得的對應表的字段信息
var no                = 0;        //為防止出現重復id保存的計數器
//添加條件編輯行
 
function addTerm(tbPanelId)
{
    tbPanel = document.getElementById(tbPanelId);
    if(tableName == null) tableName = document.getElementById("transValue").value;
    
    // 添加一待填模板行
    var row    = tbPanel.insertRow();
    no++;
    row.id = "row"+no;
    
    //*****************************step 1:添加字段選擇部分*****************************
    var cell            = row.insertCell();
    var fieldInputId    = "fIEld"+row.id;
    var newElement        = document.createElement("<SELECT ID='"+fIEldInputId+"' onchange='Javascript:getOpts("+row.id+");getInput("+row.id+")'></SELECT>");
    
    cell.insertBefore(newElement);
    
    //取出字段信息,首次從服務端取得
    if(fIEldsInfo == null)
    {
        fIEldsInfo = WebUI.AjaxSearchSystem.AJaxSearchMethod.GetFIElds(tableName.toString()).value;
    }
    
    //分解字段信息,格式為“字段中文名|字段名”
 
    var fIEldsInfoLen;
    var i,index;
    var fIEldValue;
    
    fieldsInfoLen = fIEldsInfo.length
    
    for(i=0;i<fIEldsInfoLen;i++)
    {
        fieldValue = fIEldsInfo[i];
        index = fIEldValue.indexOf("|");
        newElement.options[newElement.options.length] = new Option(fieldValue.substring(0,index),fieldValue.substring(index+1,fIEldValue.length));
    }
    
    //*****************************step 2:提取默認(首個)字段對應的運算符*************
    cell = row.insertCell();
    var optInputId = "opt" +row.id;
    newElement = document.createElement("<SELECT ID='"+optInputId+"' style='WIDTH: 88px'></SELECT>");
    cell.insertBefore(newElement);
    
    getOpts(row);
    
    //*****************************step 3:設置字段條件值的錄入(選擇)框***************
    getInput(row);
    
    //*****************************step 4:生成連接條件選擇框***************************
    cell = row.insertCell();
    var relateInputId = "relate"+row.id;
    newElement = document.createElement("<SELECT ID='"+relateInputId+"'></SELECT>");
    cell.insertBefore(newElement);
    newElement.options[newElement.options.length] = new Option("並且","And");
    newElement.options[newElement.options.length] = new Option("或者","Or");
    
    //*****************************step 5:生成刪除當前行按紐***************************
    cell = row.insertCell();
    var deleteBtnId = "delete"+row.id;
    newElement = document.createElement("<INPUT ID='"+deleteBtnId+"' type='Button' class='redButtonCSS' value='刪除' onclick='Javascript:DelRow("+row.id+")'>");
    cell.insertBefore(newElement);
    
    //*****************************step 6:生成增加下一行按紐***************************
    cell = row.insertCell();
    var addBtnId = "add"+row.id;
    newElement = document.createElement("<INPUT ID='"+addBtnId+"' type='Button' class='redButtonCSS' value='新增' onclick='Javascript:addRow("+row.id+")'>");
    cell.insertBefore(newElement);
}
 
//取得並設置運算符
function getOpts(row)
{
    var rowId = row.id;
    
    var fieldSelId = "fIEld"+rowId;
    var field = document.getElementById(fIEldSelId);
    
    var elemID = "opt"+rowId;
    var element = document.getElementById(elemID);
    
    var optInfo = WebUI.AjaxSearchSystem.AJaxSearchMethod.GetOpts(tableName.toString(),fIEld.value).value;
    var optValue;
    var j,index;
 
    //先移除原有項
    while (element.options.length > 0) 
    {    
        element.options.remove(element.options.length-1);
    }
    
    for(j=0;j<optInfo.length;j++)
    {
        optValue = optInfo[j];
        index = optValue.indexOf("|");
        element.options[element.options.length] = new Option(optValue.substring(0,index),optValue.substring(index+1,optValue.length));
    }
}
 
//設置值錄入控件,取得可能存在的枚舉值
 
function getInput(row)
{
    var rowId = row.id;
    
    var fieldSelId = "fIEld"+rowId;
    var field = document.getElementById(fIEldSelId);
    
    var inputId = "input"+rowId;
    var inputElement = document.getElementById(inputId);
    
    if (inputElement != null)
    {
        row.deleteCell(2);
    }
    
    //獲取可能存在的枚舉值
 
    var enums = WebUI.AjaxSearchSystem.AJaxSearchMethod.GetEnums(tableName.toString(),fIEld.value).value;
    var oCell;
    
    if (enums.length <= 1)//不存在枚舉值,使用text
    {
        var elementSyntax = "<INPUT ID='"+elemID+"' type='text' style='WIDTH: 144px'>";
        oCell = row.insertCell(2);
        var elemID = "input"+rowId;
        
        switch(enums[0])
        {
            case "int":
                elementSyntax = "<INPUT ID='"+elemID+"' type='text' style='WIDTH: 144px' onKeyPress='Javascript:return controlNumberKeyPress(this)' onKeyUp='return controlNumberOnKeyUp(this)' return !clipboardData.getData(\"text\").match(/\D/);'>"
                break;
            case "decimal":
                elementSyntax = "<INPUT ID='"+elemID+"' type='text' style='WIDTH: 144px' onKeyPress='Javascript:return controlMoneyKeyPress(this)' onKeyUp='return controlMoneyOnKeyUp(this,10,4)' return !clipboardData.getData(\"text\").match(/\D/);'>"
                break;
            case "datetime":
                elementSyntax = "<INPUT ID='"+elemID+"' type='text' style='WIDTH: 144px' >"
                break;
            default:
                elementSyntax = "<INPUT ID='"+elemID+"' type='text' style='WIDTH: 144px'>"
                break;
        }
                
        var oNewItem = document.createElement(elementSyntax);
        oCell.insertBefore(oNewItem);
    }
    else //存在枚舉值,使用select
    {
        oCell = row.insertCell(2);
        var elemID = "input"+rowId;
        var oNewItem = document.createElement("<SELECT ID='"+elemID+"' style='WIDTH: 144px'></SELECT>");
        oCell.insertBefore(oNewItem);
        
        var enumValue;
        var j,index;
        var element = document.getElementById(elemID);
        
        for(j=1;j<enums.length;j++)
        {
            enumValue = enums[j];
            index = enumValue.indexOf("|");
            element.options[element.options.length] = new Option(enumValue.substring(0,index),enumValue.substring(index+1,enumValue.length));
        }
    }
    
    //用於值的數據類型
    var fIEldType= document.createElement("<INPUT id='type"+rowId+"'type='hidden'>");
    oCell.insertBefore(fIEldType);
    document.getElementById("type"+rowId).value = enums[0];
}
 
//刪除當前行
 
function DelRow(row)
{
    var rowOfIndex = row.rowIndex;
    
    if(tbPanel.rows.length == 1)
    {
        return
    }
    else if (rowOfIndex == tbPanel.rows.length-1)
    {
        //刪除最後一行時,保持增加按紐在最後一行
 
        var cell = tbPanel.rows[rowOfIndex-1].insertCell();
        var addBtnId = "add"+tbPanel.rows[rowOfIndex-1].id;
        newElement = document.createElement("<INPUT ID='"+addBtnId+"' type='Button' class='redButtonCSS' value='新增' onclick='Javascript:addRow("+tbPanel.rows[rowOfIndex-1].id+")'>");
        cell.insertBefore(newElement);
    }
    
    tbPanel.deleteRow(rowOfIndex);
}
 
//新增行
 
function addRow(row)
{
    row.deleteCell(5);
    addTerm(tbPanel.id);
}
 
//得到組合條件
function getCombinTerm()
{
    var lenOfRows = tbPanel.rows.length;
    var i=0;
    var combinTerm = "";
    var field="",opt="",inputValue="",jointMode="",fIEldType="";
    
    for(i=0;i<lenOfRows;i++)
    {
        fIEld        = tbPanel.rows[i].cells[0].childNodes[0].value;
        opt            = tbPanel.rows[i].cells[1].childNodes[0].value;
        inputValue    = tbPanel.rows[i].cells[2].childNodes[0].value;
        
        //判斷字段類型
        fIEldType =tbPanel.rows[i].cells[2].childNodes[1].value;
        switch(fIEldType)
        {
            case "char":
                if (inputValue == ""|| inputValue == null)
                {
                    if(opt.toLowerCase() == "like" || opt.toLowerCase() == "not like")
                    {
                        inputValue = "'%%'";
                    }
                    else
                    {
                        inputValue = "''";
                    }
                }
                else
                {
                    if(opt.toLowerCase() == "like" || opt.toLowerCase() == "not like")
                    {
                        inputValue = "'%"+inputValue+"%'"
                    }
                    else
                    {
                        inputValue = "'"+inputValue+"'"
                    }
                    
                }
                break;
            case "int":
                if (inputValue == ""|| inputValue == null) inputValue = 0;
                break;
            case "decimal":
                if (inputValue == ""|| inputValue == null) inputValue = 0;
                break;
            case "datetime":
                if (inputValue == ""|| inputValue == null)
                {
                    inputValue = "''";
                }
                else
                {
                    inputValue = "'"+inputValue+"'"
                }
                break;
            default:
                break;
        }
        
        //拼接條件
        combinTerm += " "+tableName+"."+fIEld + " " + opt + " " + inputValue;
        
        if (i<lenOfRows-1)
        {
            jointMode    = tbPanel.rows[i].cells[3].childNodes[0].value;
            combinTerm += " " + jointMode
        }
    }
    
    document.getElementById("transValue").value = combinTerm;
    //return combinTerm;
}
 
//
var oldValue = "";
var MONEY_FLAG = "";
var THOUSAND_FLAG = ",";
 
function controlNumberKeyPress(textbox)
{
    oldValue = textbox.value.replace(MONEY_FLAG,'');
    
    return /\d/.test(String.fromCharCode(event.keyCode))||(textbox.value.indexOf('+')<0?String.fromCharCode(event.keyCode)=="+":false);
}
 
//
function controlMoneyKeyPress(textbox)
{
    var val = textbox.value.replace(MONEY_FLAG,'');
 
    if(isNumber(event.keyCode))
    {
        return true;
    }
    
    if (textbox.value.indexOf('+') < 0)
    {
        if ( String.fromCharCode(event.keyCode)=="+" && val.length < 1)
            return true;
    }
 
    if ( textbox.value.indexOf('.') < 0)
    {
        if (String.fromCharCode(event.keyCode)==".")
            return true;
    }
 
    return false;
}
 
//控制金額錄入keyUp事件
function controlNumberOnKeyUp(textbox)
{
    //處理"後退"鍵
    //alert(event.keyCode);
    if (event.keyCode == 8)
    {
        return true;
    }
 
    if (String.fromCharCode(event.keyCode) != '\t' && event.keyCode != 13)
    {
        if( !/\d/.test(String.fromCharCode(event.keyCode)) &&
            event.keyCode != 190/**//* 如果錄入"."則不執行 */ )
        {
            //textbox.value = "";
            textbox.value = oldValue;
            oldValue = textbox.value;
            return false;
        }
    }
    
    return true;
}
 
 
 
//控制金額錄入keyUp事件
function controlMoneyOnKeyUp(textbox, intBit , dotBit)
{
    //處理"後退"鍵
 
    if (event.keyCode == 8)
    {
        if (textbox.value.indexOf(MONEY_FLAG) < 0)
        {
            textbox.value = MONEY_FLAG + textbox.value;
        }
        return true;
    }
 
    if (String.fromCharCode(event.keyCode) != '\t' && event.keyCode != 13)
    {
        if( ! isNumber (event.keyCode) &&
            event.keyCode != 190/**//* 如果錄入"."則不執行 */ )
        {
            //textbox.value = "";
            textbox.value = MONEY_FLAG + oldValue;
            oldValue = textbox.value.replace(MONEY_FLAG,"");
            return false;
        }
 
        textbox.value = MONEY_FLAG + textbox.value.replace(MONEY_FLAG,'');
 
        var val = textbox.value;
        var dotBehind = "";
 
        
        val = val.replace(MONEY_FLAG,'').replace(/\,/g,'');
        var iIndex = val.indexOf('.');
        if (iIndex > 0)
        {
            var valDot = val.substring(val.indexOf('.') + 1,val.length);
            if (iIndex > intBit)
            {
                val = val.substring(0,intBit);
            }
            
            if (valDot.length > dotBit)
            {
                textbox.value = addThousandFlag(val.substring(0,val.indexOf('.'))) + '.' + valDot.substring(0,dotBit);
                return;
            }
 
            dotBehind = val.substring(val.indexOf('.'),val.length);
            val = val.substring(0,val.indexOf('.'));
        }
        else if (val.length >= intBit)
        {
            if (val.length > intBit)
            {
                val = val.substring(0,intBit);
                val = addThousandFlag(val);
            }
            textbox.value = val + '.';
            return;
        }
 
        //val = noOtherInfoNumber;
        textbox.value = addThousandFlag(val) + dotBehind;
    }
}
 
 
//添加千分位號
function addThousandFlag(val)
{
    var strTemp = MONEY_FLAG;
    if (val.length < 4)
    {
        return MONEY_FLAG + val;
    }
 
    var flag = false;
    if (val.length % 3 != 0)
    {
        strTemp += val.substring(0,(val.length % 3));
    }
    else
        flag = true;
 
    for(var i = val.length; i > 0; i = i - 1)
    {
        if (i % 3 != 0)
        {
            continue;
        }
        
        if (flag)
        {
            strTemp += val.substring(val.length - i,val.length - i + 3);
            flag = false;
        }
        else
        {
            strTemp += THOUSAND_FLAG + val.substring(val.length - i,val.length - i + 3);
        }
    }
 
    if (strTemp.indexOf(MONEY_FLAG) > 0)
    {
        strTemp = MONEY_FLAG + strTemp.replace(/¥/g,'');
    }
 
    return strTemp;
}
 
//判斷是否是數字
 
function isNumber(param)
{
    return /\d/.test(String.fromCharCode(param)) ||  (param >= 96 && param <= 105);//加上小鍵盤處理
 
} 4.AjaxSeachPage.aspx <%@ Page language="c#" Codebehind="AJaxSeachPage.ASPx.cs" AutoEventWireup="false" Inherits="WebUI.AjaxSearchSystem.AJaxSeachPage" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD Html 4.0 Transitional//EN" >
<Html>
    <HEAD>
        <title>查詢條件</title>
        <meta content="Microsoft Visual Studio .Net 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClIEntScript">
        <meta content="http://schemas.microsoft.com/intellisense/IE5" name="vs_targetSchema">
        <base target="_self">
        <LINK href="BasicStyle.css" type="text/CSS" rel="stylesheet">
        <script language="Javascript" src="AJaxSearchClIEntScript.JS">
        </script>
        <script language="Javascript" src="Calendar.JS"></script>
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <TABLE id="Table1" style="Z-INDEX: 101; LEFT: 0px; POSITION: absolute; TOP: 0px" cellSpacing="0"
                cellPadding="0" width="100%" border="0">
                <TR>
                    <TD style="HEIGHT: 23px" align="center"><asp:button id="btnOK" runat="server" CssClass="redButtonCSS" Text="確定"></ASP:button><INPUT class="redButtonCSS" type="button" value="取消" >
                    </TD>
                </TR>
                <TR>
                    <TD align="center">
                        <TABLE id="tbPanel" cellSpacing="0" borderColorDark="aliceblue" cellPadding="0" border="1">
                        </TABLE>
                    </TD>
                </TR>
                <TR>
                    <TD align="center"></TD>
                </TR>
            </TABLE>
            <INPUT id="transValue" style="Z-INDEX: 102; LEFT: 8px; POSITION: absolute; TOP: 64px" type="hidden"
                name="Hidden1" runat="server">
        </form>
    </body>
</Html>
 
AJaxSeachPage.ASPx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
 
namespace WebUI.AJaxSearchSystem
{
    /// <summary>
    /// AJaxSeachPage 的摘要說明。
    /// </summary>
    public class AJaxSeachPage : System.Web.UI.Page
    {
        protected System.Web.UI.HtmlControls.HtmlInputHidden transValue;
        protected System.Web.UI.WebControls.Button btnOK;
        public const string SEARCH_WHERE_SESSION = "SearchWhere";
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    //tableName.Value = Request.QueryString["table"].Trim();
                    transValue.Value = "employee";
                }
                catch(NullReferenceException ee)
                {
                    throw new ArgumentOutOfRangeException("table","參數不正確,請傳入預先定義的表名");
                }
            
 
                AjaxPro.Utility.RegisterTypeForAjax(typeof(AJaxSearchMethod));
            
                this.btnOK.Attributes.Add("OnClick","getCombinTerm()");
            }
        }
 
        #region Web 窗體設計器生成的代碼
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: 該調用是 ASP.Net Web 窗體設計器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <summary>
        /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
        /// 此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {    
            this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
            this.Load += new System.EventHandler(this.Page_Load);
 
        }
        #endregion
 
        private void btnOK_Click(object sender, System.EventArgs e)
        {
            Session[SEARCH_WHERE_SESSION] = transValue.Value.Trim();
 
            Response.Write(ClosePage());
        }
 
        private string ClosePage()
        {
            StringBuilder JS = new StringBuilder();
            JS.Append("<script language=\"JavaScript\">");
            JS.Append("window.close();");
            JS.Append("</script>");
            return JS.ToString();
        }
    }
}
 
運行效果:


下載源碼 AJaxGeneralSearch.rar
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved