DIV CSS 佈局教程網

在 JS 中取得資料庫數值並回填頁面的方法
編輯:JavaScript綜合知識     

專案中常會遇到「需要在 JavaScript 中讀取資料庫的值,再回填到頁面」的需求。此處採用 Ajax 方案來實現,並借助 ajax.dll 這個方便的技巧類庫。

實施步驟

1. 引用 Ajax.dll。

2. 在 App_Code 中撰寫具體方法,建議另外建立一個類別檔來放这些方法:

public class AjaxMethod
{
    [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
    public static string GetCardMoney(string cardNo, string cardPwd)
    {
        string mConn = IConfiguration.getParameter("connectString");
        IDBOSQL.IDBO dbo = IDBOSQL.IDBO.getIDBO(mConn);
        dbo.openDatabase();
        DataSet ds = dbo.executeSelectSql("select Card_Money,Service_Discount,Good_Discount "
            + "from Table_CardInfo join Dic_CardType on Table_CardInfo.CardType_ID = Dic_CardType.CardType_ID "
            + "where Card_NO='" + cardNo + "' and Card_Pwd='" + cardPwd + "' and card_Status='正常'");
        DataTable dt = ds.Tables[0];
        string money = dt.Rows[0][0].ToString();
        string service_discount = dt.Rows[0][1].ToString();
        string good_discount = dt.Rows[0][2].ToString();
        dbo.closeDatabase();
        // 回傳多個值以逗號串接的字串
        return money + "," + service_discount + "," + good_discount;
    }
}

3. 在 JS 中呼叫:

moneydiscount = AjaxMethod.GetCardMoney(card, pwd).value;
// 把串接字串轉為陣列,方便使用多個值
arr = moneydiscount.split(",");

4. 把結果回填到頁面:

document.getElementById("txtCard_Money1").value = arr[0];

5. 在 Web.config 中註冊:

<httpHandlers>
    <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
</httpHandlers>

透過這種「後端方法回傳串接字串、前端 split 成陣列」的組合,就能很便利地用 Ajax 一次取得並使用多個數值。

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