DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
用 AJAX 做出網易相冊風格的即時編輯效果
編輯:AJAX詳解     

這個範例示範如何把一般的 AJAX 呼叫與 JavaScript 對 HTML 元素的動態操作結合起來,做出滑過高亮、點擊就地編輯、存檔後立刻回寫的相冊描述效果。使用的仍是 Ajax.NET,設定方式與前一篇文章相同,此處不再重複。

後端:讀取與更新描述

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;

public partial class _163photoTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        description.Text = GetDescription();
        AjaxPro.Utility.RegisterTypeForAJax(typeof(_163photoTest));
    }

    // 讀取資料庫中的描述
    protected string GetDescription()
    {
        try
        {
            string strComm = "select photo_description from tab_photo where photo_id=1";
            SqlConnection myConn = new SqlConnection(
                ConfigurationManager.ConnectionStrings["test"].ConnectionString);
            myConn.Open();
            SqlCommand myComm = new SqlCommand(strComm, myConn);
            SqlDataReader myReader = myComm.ExecuteReader();
            myReader.Read();
            return myReader.GetString(0);
        }
        catch
        {
            return "";
        }
    }

    // 將描述寫回資料庫
    [AjaxPro.AjaxMethod]
    public bool UpdateDesc(string description)
    {
        try
        {
            string strComm = "update tab_photo set photo_description=@desc where photo_id=1";
            SqlConnection myConn = new SqlConnection(
                ConfigurationManager.ConnectionStrings["test"].ConnectionString);
            myConn.Open();
            SqlCommand myComm = new SqlCommand(strComm, myConn);
            myComm.Parameters.AddWithValue("@desc", description);
            myComm.ExecuteNonQuery();
            return true;
        }
        catch
        {
            return false;
        }
    }
}

要能被前端直接呼叫的方法必須標上 [AjaxPro.AjaxMethod],並在 Page_Load 中呼叫 RegisterTypeForAJax 註冊型別,兩者缺一不可。

前端:切換顯示與編輯狀態

<%@ Page Language="C#" AutoEventWireup="true"
    CodeFile="163photoTest.aspx.cs" Inherits="_163photoTest" %>
<!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 language="javascript" type="text/javascript">
    function display() {
      document.getElementById('descField').style.display = 'block';
      document.getElementById('descField').value =
        document.getElementById('description').innerText;
      document.getElementById('description').style.display = 'none';
      document.getElementById('save').style.display = 'block';
    }
    var s;
    function UpdateDesc() {
      s = document.getElementById("descField").value;
      document.getElementById("descField").value = "正在儲存";
      _163photoTest.UpdateDesc(s, UpdateDesc_callback);
    }
    function UpdateDesc_callback(res) {
      if (res) {
        document.getElementById('description').style.display = 'block';
        document.getElementById("description").innerText = s;
        document.getElementById('descField').style.display = 'none';
        document.getElementById('save').style.display = 'none';
      }
    }
  </script>
</head>
<body onload="document.getElementById('descField').style.display='none';
               document.getElementById('save').style.display='none';">
  <form id="form1" runat="server">
  <div>
    <div id="div1"
         onmouseover="this.style.backgroundColor='#C0C0FF';"
         onmouseout="this.style.backgroundColor='';"
         onclick="display()">
      <asp:Label ID="description" runat="server" Text="Label"></asp:Label>
    </div>
    <input type="text" id="descField" />
    <input type="button" id="update" value="修改描述" onclick="display()" />
    <input type="button" id="save" value="儲存修改" onclick="UpdateDesc()" />
  </div>
  </form>
</body>
</html>

效果與幾個要注意的地方

滑過描述區塊時底色變為淺藍,離開後還原;點擊後文字方塊取代原本的 Label,並出現「儲存修改」按鈕。按下儲存後,前端會立刻把欄位內容換成「正在儲存」,等 AJAX 回呼收到 true 再把新文字寫回 Label、隱藏輸入區,整個過程頁面不會刷新。

原範例把資料庫連線字串(含帳號與密碼)直接寫在程式碼裡,並以字串拼接組出 UPDATE 語句。這在正式環境中是明確的風險:憑證外洩與 SQL Injection 都由此而來。上面已改成從 web.config 的連線字串設定讀取,並改用參數化查詢。另外,Ajax.NET 屬性名稱的大小寫需與註冊的版本一致(AjaxMethod 或 AjaxPro.AjaxMethod),這也是常見的踩雷點。

出處:Coder at the Doorsill——風中聆聽 BLOG

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