简易ajax留言板

2019-08-14 17:44 更新

先来看下具体的效果图:

ajax留言板

思路很简单,就是一般的Ajax系统,主要是里面的一些jQuery的特效确实不错。下面是实现步骤:

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

 

1. 首先设计数据库,很简单,留言人、留言时间、留言内容、头像等字段,具体的数据库表创建语句如下

ajax

4. 使用div 及css 布局你的留言板页面,参考http://www.css88.com/demo/ajax-deleet 中的布局;

5. 当初为了方便起见,使用了最基础的SQL Helper作为数据操作类,下面是该 SQL Helper类的代码:


代码

/*

 * 文件名:SQLHelper

 * 说明:SQL Server帮助类

 * 作者:Alexis

 * 网站:http://www.cnblogs.com/alexis

 * 创建时间: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;

/// <summary>

///SQLHelper 的摘要说明

/// </summary>

public class SQLHelper

{

    SqlConnection conn;

    public SQLHelper()

    {

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

        conn = new SqlConnection(connectionString);

    }


    /// <summary>

    /// 执行SQL命令,将数据赋给数据集的引用

    /// </summary>

    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;

    }


    /// <summary>

    /// 执行带参数的SQL语句

    /// </summary>

    /// <param name="cmdText"></param>

    /// <param name="sp"></param>

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

    {

        try

        {

            if(conn.State== ConnectionState.Closed)

                conn.Open();

            SqlCommand cmd = new SqlCommand(cmdText, conn);

            if (sp != null)

            {

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

                {

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

                }

            }

            cmd.ExecuteNonQuery();

        }

        catch (SqlException se)

        {

            return false;

            throw new Exception(se.Message, se);

        }

        finally

        {

            conn.Close();

        }

        return true;

    }

    public DataTable getDataTable(string cmdText)

    {

        DataTable dt = null;

        try

        {

            if (conn.State == ConnectionState.Closed)

                conn.Open();

            SqlCommand cmd = new SqlCommand(cmdText, conn);

            DataSet ds = new DataSet();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

            dt = ds.Tables[0];

        }

        catch (SqlException se)

        {

            throw new Exception(se.Message, se);

        }

        finally

        {

            conn.Close();

        }

        return dt;

    }

}


6. 创建数据库对象的实体类,也是十分简单的,就是对应数据库的字段;

代码

/*

 * 文件名:Message

 * 说明:Message实体类

 * 作者:Alexis

 * 网站:http://www.cnblogs.com/alexis

 * 创建时间:20100428

 * */

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace MessageBoard

{

    /// <summary>

    /// 留言类

    /// </summary>

    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文本框水印效果,效果图如下:

w3cschool

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

<input type="text" id="msg_nickname" size="40" /> 之后再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) + "&msg_content=" + escape(msg_content) + "&msg_time=" + msg_time + "&msg_face=" + msg_face,



                    success: function (msg) {



                        //在table中新增一行



                        if (msg == "success") {



                            $('#messagelist').append("<div class='box clearfix' id=''><img src='" + msg_face +



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



                        }



                    }



                });



上面的一些变量重字面上也能知道是我们收集的信息,即要写如数据库的留言信息;


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")//删除留言

            {

            }

        }


        /// <summary>

        /// 新增留言

        /// </summary>

        /// <param name="message"></param>

        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的留言板

 * 作者:Alexis

 * 网站:http://www.cnblogs.com/alexis

 * 创建时间:20101226

 * */

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;


namespace MessageBoard

{

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

    {

        protected DataTable dt;

        protected void Page_Load(object sender, EventArgs e)

        {

            GetMessage();

        }


        //从数据库中读取留言信息

        protected void GetMessage()

        {

            SQLHelper helper = new SQLHelper();

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

        }

    }

}


12. 在前台显示这些数据,使用的内部变量,即 <%=dt.Rows[i]["msg_time"]%>这种形式的代码,详细的代码可以参考源文件


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号