天天看點

Ajax留言闆

在整理以前資料時偶爾發現有一個效果不錯的Ajax留言闆程式,是以前一個系統的一個部分。今天抽了點時間,将其獨立成一個項目,與大家分享下,先來看下具體的效果圖:

<a target="_blank" href="http://blog.51cto.com/attachment/201105/145316199.jpg"></a>

思路很簡單,就是一般的Ajax系統,主要是裡面的一些jQuery的特效确實不錯。下面是實作步驟:

環境:Visual Studio 2010 + SQL Server 2008 + jQuery1.4.1

1. 首先設計資料庫,很簡單,留言人、留言時間、留言内容、頭像等字段,具體的資料庫表建立語句如下

CREATE TABLE [dbo].[tb_message_board](  

    [MSG_ID] [int] IDENTITY(1,1) NOT NULL,  

    [MSG_USER] [nchar](20) NULL,  

    [MSG_FACE] [nchar](50) NULL,  

    [MSG_CONTENT] [nchar](100) NULL,  

    [MSG_TIME] [datetime] NULL  

) ON [PRIMARY] 

大家可以在自己機器上執行該SQL ,你項目的資料庫,同時要修改Web.config中的資料庫名;

2. 建立ASP.NET 應用程式,預設已經有母版頁了,我們隻要添加一個使用了預設母版頁的Web頁面,取名為MessageBoard;

3. 建立一些常用的檔案夾,如images檔案夾,用來存放項目中使用的圖檔,我這邊最後建立後的解決方案管理器如下圖:

<a target="_blank" href="http://blog.51cto.com/attachment/201105/145407579.jpg"></a>

4. 使用div 及css 布局你的留言闆頁面,我之前參考了http://www.css88.com/demo/ajax-deleet 中的布局;

5. 當初為了友善起見,使用了最基礎的SQL Helper作為資料操作類,下面是該 SQL Helper類的代碼:

/*  

 * 檔案名:SQLHelper  

 * 說明:SQL Server幫助類  

 * 作者:Alexis  

 * 網站:http://alexis.blog.51cto.com/  

 * 建立時間:20100428  

 * */  

using System;  

using System.Data;  

using System.Configuration;  

using System.Linq;  

using System.Web;  

using System.Web.Security;  

using System.Web.UI;  

using System.Web.UI.HtmlControls;  

using System.Web.UI.WebControls;  

using System.Web.UI.WebControls.WebParts;  

using System.Xml.Linq;  

using System.Data.SqlClient;  

/// &lt;summary&gt; 

///SQLHelper 的摘要說明  

/// &lt;/summary&gt; 

public class SQLHelper  

{  

    SqlConnection conn;  

    public SQLHelper()  

    {  

        string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MessageBoard"].ToString();  

        conn = new SqlConnection(connectionString);  

    }  

    /// &lt;summary&gt; 

    /// 執行SQL指令,将資料賦給資料集的引用  

    /// &lt;/summary&gt; 

    public bool RunSQL(string cmdText, ref DataTable dt)  

        try  

        {  

            conn.Open();  

            SqlCommand cmd = new SqlCommand(cmdText, conn);  

            SqlDataAdapter sda = new SqlDataAdapter(cmd);  

            DataSet ds1 = new DataSet();  

            sda.Fill(ds1);  

            dt = ds1.Tables[0];  

        }  

        catch (SqlException se)  

            return false;  

            throw new Exception(se.Message, se);  

        return true;  

    /// 執行帶參數的SQL語句  

    /// &lt;param name="cmdText"&gt;&lt;/param&gt; 

    /// &lt;param name="sp"&gt;&lt;/param&gt; 

    public bool RunSQL(string cmdText, SqlParameter[] sp)  

            if(conn.State== ConnectionState.Closed)  

                conn.Open();  

            if (sp != null)  

            {  

                for (int i = 0; i &lt; sp.Length; i++)  

                {  

                    cmd.Parameters.Add(sp[i]);//将參數加到Command中  

                }  

            }  

            cmd.ExecuteNonQuery();  

        finally  

            conn.Close();  

    public DataTable getDataTable(string cmdText)  

        DataTable dt = null;  

            if (conn.State == ConnectionState.Closed)  

            DataSet ds = new DataSet();  

            SqlDataAdapter da = new SqlDataAdapter(cmd);  

            da.Fill(ds);  

            dt = ds.Tables[0];  

        return dt;  

}  

6. 建立資料庫對象的實體類,也是十分簡單的,就是對應資料庫的字段;

 * 檔案名:Message  

 * 說明:Message實體類  

 * 網站:http://alexis.blog.51cto.com/

using System.Collections.Generic;  

namespace MessageBoard  

    /// 留言類  

    public class Message  

        private int id;//留言的辨別  

        public int Id  

            get { return id; }  

            set { id = value; }  

        private string msg_content;//留言的内容  

        public string Msg_content  

            get { return msg_content; }  

            set { msg_content = value; }  

        private string msg_nickname;// 昵稱  

        public string Msg_nickname  

            get { return msg_nickname; }  

            set { msg_nickname = value; }  

        private string msg_face;//選擇的頭像  

        public string Msg_face  

            get { return msg_face; }  

            set { msg_face = value; }  

        private DateTime msg_time;//留言的時間  

        public DateTime Msg_time  

            get { return msg_time; }  

            set { msg_time = value; }  

7.開始着手寫js代碼,在寫ajax事件之前,先來看下兩個jQuery插件,首先是jQuery文本框水印效果,效果圖如下:

<a target="_blank" href="http://blog.51cto.com/attachment/201105/150046260.jpg"></a>

 使用方法:添加watermarkinput 的js引用,為想要實作水印效果的文本框加上id如,

&lt;input type="text" id="msg_nickname" size="40" /&gt; 之後再js代碼中寫如下的代碼以處理水印//處理水印  

        jQuery(function ($) {  

            $("#msg_nickname").Watermark("請輸入您的昵稱,如果不輸入則預設為匿名");  

        });  

        function UseData() {  

            $.Watermark.HideAll();   //Do Stuff     

            $.Watermark.ShowAll();  

        } 

8. jQuery圖檔縮放插件,jquery.imgzoom.js ,具體的效果:點選圖示的時候,圖檔漸漸變大,直至原來的大小,如果是Gif圖檔的話,效果會更好。

9. 編寫具體的Ajax代碼,使用jQuery架構将會節省很多的時間,當我們點選留言按鈕的時候,将一些資訊收集起來,然後通過Ajax寫入資料庫,然後使用布局修改DOM來實作無重新整理的效果,主要的代碼如下:

//使用ajax處理留言  

                $.ajax({  

                    type: "POST",  

                    url: "Ajax/MessageBoardHandler.ashx?action=add",  

                    data: "msg_nickname=" + escape(msg_nickname) + "&amp;msg_content=" + escape(msg_content) + "&amp;msg_time=" + msg_time + "&amp;msg_face=" + msg_face,  

                    success: function (msg) {  

                        //在table中新增一行  

                        if (msg == "success") {  

                            $('#messagelist').append("&lt;div class='box clearfix' id=''&gt;&lt;img src='" + msg_face +  

                                "' alt='' width='50' height='50' class='avatar' /&gt;&lt;div class='text'&gt;&lt;strong&gt;&lt;a href='#'&gt;" + msg_nickname + "&lt;/a&gt;&lt;/strong&gt;&lt;p&gt;" + msg_content +"&lt;/p&gt;&lt;div class='date'&gt;"+msg_time+"&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;");  

                        }  

                    }  

                }); 

上面的一些變量重字面上也能知道是我們收集的資訊,即要寫如資料庫的留言資訊;

10. 編寫Ajax處理類的代碼,将資訊插入資料庫,代碼如下:

public void ProcessRequest(HttpContext context)  

            context.Response.ContentType = "text/plain";  

            string action = context.Request.Params["action"].ToString();//擷取想要做的操作  

            if (action == "add")//新增留言  

                Message message = new Message();//建立新的留言對象  

                message.Msg_nickname = context.Request.Params["msg_nickname"].ToString();//昵稱  

                message.Msg_content = context.Request.Params["msg_content"].ToString();//留言内容  

                message.Msg_time = DateTime.Parse(context.Request.Params["msg_time"].ToString());//留言時間  

                message.Msg_face = context.Request.Params["msg_face"].ToString();//選擇的頭像  

                MessageAdd(message,context);  

            else if (action=="del")//删除留言  

        /// &lt;summary&gt; 

        /// 新增留言  

        /// &lt;/summary&gt; 

        /// &lt;param name="message"&gt;&lt;/param&gt; 

        private void MessageAdd(Message message, HttpContext context)  

            SQLHelper helper = new SQLHelper();  

            string cmdText = "INSERT INTO TB_MESSAGE_BOARD(MSG_USER,MSG_CONTENT,MSG_FACE,MSG_TIME) VALUES('" +  

                message.Msg_nickname + "','" + message.Msg_content + "','" + message.Msg_face + "','" + message.Msg_time + "')";  

            if(helper.RunSQL(cmdText, null))  

                context.Response.Write("success");  

在這個類裡面就用到了SQL Helper了;

 11. 編寫MessageBoard的背景代碼,我們在加載留言本頁面的時候,需要将已有的留言資訊顯示在頁面中,

 * 檔案名:MessageBoard  

 * 說明:使用Ajax的留言闆  

 * 建立時間:20101226  

    public partial class MessageBoard : System.Web.UI.Page  

        protected DataTable dt;  

        protected void Page_Load(object sender, EventArgs e)  

            GetMessage();  

        //從資料庫中讀取留言資訊  

        protected void GetMessage()  

            dt=helper.getDataTable("select * from tb_message_board");  

12. 在前台顯示這些資料,使用的内部變量,即 &lt;%=dt.Rows[i]["msg_time"]%&gt;這種形式的代碼,詳細的代碼可以參考源檔案

<a target="_blank" href="http://alexis.blog.51cto.com/attachment/201105/2621421_1306393457.rar"></a>

<a href="http://down.51cto.com/data/2358226" target="_blank">附件:http://down.51cto.com/data/2358226</a>

    本文轉自xshf12345 51CTO部落格,原文連結:http://blog.51cto.com/alexis/574676,如需轉載請自行聯系原作者