DIV CSS 佈局教程網

jQuery + WebService:即時檢查帳號是否已被註冊
編輯:JQuery特效代碼     

註冊頁面上「帳號是否可用」的即時回饋,是使用者體驗的關鍵細節。做法是在輸入框綁定 keyup 事件,每次敲字就丟一次 AJAX 請求是後端 WebService 檢查,再把結果寫回頁面。以下完整示範。

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Ajax_XML._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="jquery-1.3.2-vsdoc2.js" language="javascript"></script>
<script type="text/javascript" language="javascript">
$(function() {
  $("#<%=UserID.ClientID%>").keyup(
    function() {
      $.ajax({
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        url: "WebService1.asmx/UserIsExist",
        data: "{UserID:'" + $("#<%=UserID.ClientID%>").val() + "'}",
        success: function(result) {
          if (result.d == "true")
            $("#<%=IsExist.ClientID%>").text("Yes"); // 帳號已存在
          else
            $("#<%=IsExist.ClientID%>").text("No");
        }
      });
    }
  );
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:100%;">
<tr><td></td><td></td><td></td></tr>
<tr>
<td></td>
<td>
  <asp:TextBox ID="UserID" runat="server"></asp:TextBox>
  <asp:Label ID="IsExist" runat="server" Visible="true"></asp:Label>
</td>
<td></td>
</tr>
<tr><td></td><td></td><td></td></tr>
</table>
</div>
</form>
</body>
</html>

幾個值得注意的地方:使用 <%= 控制項.ClientID %> 而非硬寫 ID,是因為 ASP.NET 在 NamingContainer 內會自動改寫控制項 ID,寫死會抓不到元素。result.d 這層包裝則是 ASP.NET AJAX 序列化回應的固定格式。

WebService1.asmx.cs

using System;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using DAL;

namespace Ajax_XML
{
  /// <summary>
  /// WebService1 的摘要說明
  /// </summary>
  [WebService(Namespace = "https://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  [System.ComponentModel.ToolboxItem(false)]
  // 若要允許使用 ASP.NET AJAX 從腳本中呼叫此 Web 服務,請取消對下行的註釋。
  [System.Web.Script.Services.ScriptService]
  public class WebService1 : System.Web.Services.WebService
  {
    [WebMethod]
    public string HelloWorld()
    {
      return "Hello,World!";
    }

    [WebMethod]
    public string UserIsExist(string UserID)
    {
      string sql = string.Format("select * from Customers where FirstName='" + UserID + "'");
      using (SqlDataReader dr = SqlHelper.ExecuteSql(sql))
      {
        if (dr.Read()) return "false";
        else return "true";
      }
    }
  }
}

[System.Web.Script.Services.ScriptService] 這個屬性千萬別漏掉,預設是註解狀態;沒有它,前端就無法以腳本方式呼叫 Web 方法。

SqlHelper.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace DAL
{
  /// <summary>
  /// 資料庫操作類
  /// </summary>
  public class SqlHelper
  {
    private static SqlConnection conn;
    private static SqlCommand comm;
    private static SqlDataReader dr;

    /// <summary>開啟資料庫連接</summary>
    public static void ConnOpen()
    {
      try
      {
        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BBS"].ConnectionString);
        conn.Open();
      }
      catch (Exception e)
      {
        Console.WriteLine(e.Message);
      }
    }

    /// <summary>關閉連接並釋放資源</summary>
    public static void ConnClose()
    {
      if (conn != null) conn.Close();
      if (comm != null) comm.Dispose();
    }

    public static SqlDataReader ExecuteSql(string sql)
    {
      SqlHelper.ConnOpen();
      comm = new SqlCommand(sql, conn);
      try
      {
        dr = comm.ExecuteReader();
        return dr;
      }
      catch (Exception e)
      {
        throw e;
      }
    }
  }
}

兩個必須修正的問題

範例能跑,但直接搬上 production 會出事,這裡誠實指出兩點:

一、SQL Injection。字串拼接 SQL 是最典型的注入漏洞。使用者只要輸入 ' or '1'='1 就能扭曲查詢結果。正確做法是把 UserID 轉為參數,改用 SqlCommand.Parameters.AddWithValue("@UserID", UserID),讓資料庫引擎負責處理轉義。

二、每次 keyup 都打一次請求。快速輸入十個字就送出十次查詢,對資料庫與頻寬都不友善。建議加上 debounce(例如停手 300 毫秒才送出)並取消前一次未完成的要求,同時在伺服端對輸入格式先做基本驗證。

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