DIV CSS 佈局教程網

JavaScript 透過 Ajax 取得資料庫數值的實作流程
編輯:關於JavaScript     

要在不重整頁面的情況下把資料庫的數字填進表單欄位,需要三個環節配合:後端提供可呼叫的方法、設定檔開放 Ajax 路由、前端發請求並把結果寫回頁面。以下以 ASP.NET 的 Ajax.NET 為例說明。

步驟一:引用 Ajax.dll

Ajax.NET 這類函式庫會自動把標了特定屬性的 C# 方法轉換成可由 JavaScript 呼叫的端點,省去自己寫 ashx 或 WebService 的功夫。

步驟二:在 App_Code 中撰寫方法

建議單獨建立一個類別檔,把相關方法集中管理:

public class AjaxMethod
{
    public AjaxMethod()
    {
        // TODO: 建構函式邏輯
    }

    [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;
    }
}

[Ajax.AjaxMethod] 這個 attribute 就是關鍵:它讓方法被公開為可從前端呼叫的服務,並宣告需要唯讀的 Session 存取權。

步驟三:在 JavaScript 中呼叫

moneydiscount = AjaxMethod.GetCardMoney(card, pwd).value;
// 回傳的是以逗號串接的字串,要取值先切成陣列
arr = moneydiscount.split(",");

步驟四:把結果寫回頁面

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

步驟五:在 Web.config 註冊 handler

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

這段設定把 ajax/*.ashx 路徑導向 Ajax.NET 的 handler,前面呼叫的 AjaxMethod.GetCardMoney 才會被正確解析。

這段程式碼的嚴重問題:SQL 注入

必須明確指出:上面那個查詢語句直接把 cardNo 與 cardPwd 拼進 SQL,這是典型的 SQL 注入漏洞。攻擊者只要在卡號欄輸入 ' OR '1'='1,就能跳過密碼驗證拿到所有卡片的資料;更進一步甚至能 UNION 出其他表的內容或刪除資料。

正確做法是使用參數化查詢:

string sql = "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=@no and Card_Pwd=@pwd and card_Status=@status";

SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@no",     cardNo);
cmd.Parameters.AddWithValue("@pwd",    cardPwd);
cmd.Parameters.AddWithValue("@status", "正常");

另外,密碼不該以明文比對,應該在資料庫中存雜湊值(bcrypt、PBKDF2 等),比對時對輸入做一樣的雜湊再比較。

其他該改善的地方

  • 查無資料會拋例外。dt.Rows[0] 在查不到資料時會丟出 IndexOutOfRange,應先檢查 dt.Rows.Count > 0 並回傳明確的錯誤訊息。
  • 用逗號拼字串傳多值太脆弱。一旦某個欄位本身含逗號就會錯位。應改用 JSON 回傳結構化資料。
  • 連線未用 using 保護。若查詢中途丟出例外,closeDatabase() 不會執行,連線會外洩。應改用 using 或 try/finally。
  • 前端要處理非同步。這類呼叫通常是 callback 模式,取值時機在回呼裡,不能當同步函式用。

Ajax.NET 已是歷史技術,新專案請改用 ASP.NET Web API 或 MVC 的 Controller 回傳 JSON,搭配 fetch 或 axios 於前端取用。

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