DIV CSS 佈局教程網

jQuery + Ajax 抓資料填進 ASP.NET GridView(含 loading 提示)
編輯:JQuery特效代碼     

GridView 是 WebForms 時代最順手的表格控件,但傳統的 postback 會讓整頁重載。若改成用 ajax 抓一段 HTML 回來塞進容器,就能做到「查詢時畫面不閃、只換表格那一塊」。

一、查詢頁:AJAXLoadProgressForm.aspx

<script src="JS/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowProgressDiv() {
  var ID = $("input#idtxt").val();
  $.ajax({
    type: "GET",
    url: "GetGridViewByConditionForm.aspx",
    data: "id=" + ID,
    beforeSend: function() {
      $("div#ProgressDiv").css("display", "block");   // 顯示 loading
    },
    success: function(msg) {
      $("div#ShowSearchResult").html(msg);            // 把回傳的 HTML 塞進去
    },
    complete: function() {
      $("div#ProgressDiv").css("display", "none");    // 無論成败都收起來
    }
  });
}
</script>

<form id="form1" runat="server">
<div>
  <input type="text" id="idtxt" name="idtxt" />
  <input type="button" id="LoadBtn" value="LoadDataGridView"
         onclick="ShowProgressDiv()" />
</div>
<div id="ProgressDiv" style="display:none">
  <img alt="Loading" src="Images/ajax-loader.gif" />Loading......
</div>
<div id="ShowSearchResult"></div>
</form>

這裡有兩個關鍵細節:loading 的隱藏放在 complete 而不是 success,因為查詢失敗時也必須把 loading 收起來,否則畫面會永遠卡在轉圈圈;而結果容器 #ShowSearchResult 是個單純的 div,不含 runat="server",因為它完全由前端填充,後端不需要參照它。

二、資料頁:GetGridViewByConditionForm.aspx

protected void Page_Load(object sender, EventArgs e)
{
  if (Request["id"] != null)
  {
    SqlConnection conn = null;
    SqlCommand cmd = null;
    SqlDataAdapter adapter = null;
    try
    {
      conn = new SqlConnection();
      conn.ConnectionString = ConfigurationManager
          .ConnectionStrings["NorthwindConnectionString"].ConnectionString;
      conn.Open();

      cmd = new SqlCommand();
      cmd.Connection = conn;
      cmd.CommandType = CommandType.Text;

      String cmdStr = "select * from dbo.Customers";
      if (Request["id"].ToString() != String.Empty)
        cmdStr += " where CustomerID = '" + Request["id"].ToString() + "'";

      cmd.CommandText = cmdStr;

      adapter = new SqlDataAdapter(cmd);
      DataSet ds = new DataSet();
      adapter.Fill(ds);

      this.gvData.DataSource = ds;
      this.gvData.DataBind();
    }
    catch
    {
      Response.Write("Error happend!");
      Response.Flush();
      Response.End();
    }
    finally
    {
      if (adapter != null) adapter.Dispose();
      if (cmd != null) cmd.Dispose();
      if (conn != null && conn.State == ConnectionState.Open) conn.Close();
    }
  }
}

這個頁面被 ajax 呼叫時,回傳的就是 GridView 渲染出來的 HTML 片段,前端直接 innerHTML 塞進去即可——這也是 WebForms 裡做局部更新的經典手法。

三、三個一定要改的地方

SQL Injection。cmdStr += " where CustomerID = '" + Request["id"] + "'" 是教科書級的漏洞。使用者只要在輸入框打 ' OR '1'='1,整張 Customers 表就會被拉出來。必須改成參數化查詢:

cmd.CommandText = "select * from dbo.Customers where CustomerID = @id";
cmd.Parameters.AddWithValue("@id", Request["id"]);

身分驗證與授權。這個 aspx 頁面只要被打開就能查到任何客戶資料,沒有任何登入檢查。它被設計成「被 ajax 呼叫的片段」,但實際上任何人用瀏覽器直接拜訪都拿得到資料。正式環境請在 Page_Load 開頭加上身分驗證,或把它改成真正的 Web API 端點並掛上授權。

不要用 GET 傳送查詢條件。查詢字串會留在瀏覽器歷史與伺服器日誌裡,條件稍長也可能超過網址長度上限;改 POST 較合適。

四、如果你今天才要做這件事

WebForms 加 GridView 加字串拼接 HTML 這條路,適合用來維護既有系統。若是新專案,前端用 fetch 或 axios 抓 JSON,再用模板或框架渲染表格,會比「後端吐 HTML 片段、前端整段替換」更好維護——後者的每個狀態都得由後端重新渲染,前端難以做排序、篩選、分頁等互動。

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