Ajax模擬留言

create table UserInfo
(
 username varchar(20),
 userpwd varchar(20)
)
 
insert into UserInfo values('administrator','123456')
create table ChatInfo
(
   id int identity(1,1)  primary key,
  [name] varchar(20),
   context varchar(20),
   chattime datetime
)


         <add verb="*" path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>

    <system.web>
      <!--防止亂碼-->
      <globalization fileEncoding="GB2312" requestEncoding="GB2312" responseEncoding="GB2312"/>

  public class Userinfo
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string pwd;

        public string Pwd
        {
            get { return pwd; }
            set { pwd = value; }
        }
    }


 

 public class ChatInfo
    {
        private string id;

        public string Id
        {
            get { return id; }
            set { id = value; }
        }
        private string context;

        public string Context
        {
            get { return context; }
            set { context = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string time;

        public string Time
        {
            get { return time; }
            set { time = value; }
        }

        public override string ToString()
        {
            return string.Format("{0} 說 {1} 時間{2}", name, context, time);
        }
    }

 

  public class DBHelper
    {
        private SqlConnection sqlconn = null;
        private SqlCommand sqlcmd = null;
        private SqlDataReader sqlread = null;
        private static DBHelper db = null;
        private DBHelper()
        {
            sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlDB"].ToString());

        }
        /// <summary>
        /// 單例
        /// </summary>
        /// <returns></returns>
        public static DBHelper createInstance()
        {
            if (db == null)
            {
                db = new DBHelper();
            }
            return db;
        }
        public bool checkLogin(Userinfo user)
        {
            string sql = string.Format("select count(*) from userinfo where username='{0}' and userpwd='{1}'",user.Name,user.Pwd);
            sqlcmd = new SqlCommand(sql,sqlconn);
            try
            {
                sqlconn.Open();
                return (int)sqlcmd.ExecuteScalar() == 1;
            }
            catch
            {

                return false;
            }
            finally
            {
                sqlconn.Close();
            }
        }
        //發言
        public bool sendChat(ChatInfo chat)
        {
            string sql = string.Format("insert into ChatInfo values('{0}','{1}','{2}')",chat.Context,chat.Name,DateTime.Now.ToString());
            sqlcmd=new SqlCommand(sql,sqlconn);
            try
            {
                sqlconn.Open();
                return sqlcmd.ExecuteNonQuery() > 0;
            }
            catch
            {

                return false;
            }
            finally
            {
                sqlconn.Close();
            }
        }
        //顯示
        public List<ChatInfo> GetAllInfo()
        {
            string sql = "select *from Chatinfo order by chattime";
            sqlcmd = new SqlCommand(sql,sqlconn);
            try
            {
                sqlconn.Open();
                sqlcmd = new SqlCommand(sql, sqlconn);
                sqlread = sqlcmd.ExecuteReader();
                List<ChatInfo> list = new List<ChatInfo>();
                while (sqlread.Read())
                {
                    ChatInfo chat = new ChatInfo();
                    chat.Id = sqlread[0].ToString();
                    chat.Context = sqlread[1].ToString();
                    chat.Name = sqlread[2].ToString();
                    chat.Time = sqlread[3].ToString();
                    list.Add(chat);
                }
                return list;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                sqlconn.Close();
            }
        }
    }
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
    <script type="text/javascript">
        var xmlHttp;
        function createDemo() {
            if (window.ActiveXObject) {
                var ieArr = ["Msxml2.XMLHTTP.8.0", "Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
                for (var i = 0; i < ieArr.length; i++) {
                    try {
                        xmlHttp = new ActiveXObject(ieArr[i]);
                    }
                    catch (e) { } //拋異常,直到找到合適的版本
                }
            }
            else if (window.XMLHttpRequest) {
                xmlHttp = new XMLHttpRequest();
            }
        }
        //登錄
        function doDemo() {
            var name = document.getElementById("txtName").value;
            var pwd = document.getElementById("txtPwd").value;
            if (name.length < 3) {
                alert("用戶名不能少於3位!");
             
             
            }
            else if (pwd.length < 6) {
            alert("用戶密碼不能少於6位!");
           
            }
            else {
                createDemo();
                xmlHttp.onreadystatechange = disDemo; //觸發事件
                var url = "WebChat.aspx?name=" + name + "&pwd=" + pwd;
                xmlHttp.open("GET", url, true);
                xmlHttp.send();
            }
            document.getElementById("divDis").innerHTML = "";
           
       
        }
        //發言
        function sendDemo() {
            var chat = document.getElementById("txtChat").value;
            var name = document.getElementById("userName").value;
            if (chat.length == 0) {
                alert("不能空發信息");
            }
            else {
                createDemo();
                //異步請求伴隨着5種狀態的產生,只有一個事件onreadystatechange發生
                xmlHttp.onreadystatechange = disDemo;
                var url = "InsertDemo.aspx?name=" + name + "&chat=" + chat;
                //加載
                xmlHttp.open("GET", url, true);
                //發送
                xmlHttp.send();
            }
        }
        //顯示
        function disDemo() {
            if (xmlHttp.readyState == 4)// 0 - (未初始化)還沒有調用send()方法
            //1 - (載入)已調用send()方法,正在發送請求
            // 2 - (載入完成)send()方法執行完成,已經接收到全部響應內容
            //   3 - (交互)正在解析響應內容
            // 4 - (完成)響應內容解析完成,可以在客戶端調用了
            {
                if (xmlHttp.status == 200)//編號200表示成功
                {
                //responsetext 以字符串形式返回服務器的響應,responsexml 以XML形式返回服務器的響應
                    document.getElementById("divLogin").innerHTML = xmlHttp.responsetext;
                }
            }
        }
    </script>
</head>
<body>
    <div id="divDis">
    <table border="1" align="center">
        <tr>
            <td colspan="2" align="center">
                用戶登錄
            </td>
        </tr>
        <tr>
            <td>
                用戶名稱
            </td>
            <td>
                <input id="txtName" type="text" />
            </td>
        </tr>
        <tr>
            <td>
                用戶密碼
            </td>
            <td>
                <input id="txtPwd" type="password" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input id="btnLogin" type="button" value="登錄" onclick="doDemo();" />
            </td>
        </tr>
    </table>
    </div>
    <div id="divLogin"></div>
</body>
</html>


  public partial class InsertDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                string name = Request["name"];
                string chat = Request["chat"];
                ChatInfo chatInfo = new ChatInfo();
                chatInfo.Name = name;
                chatInfo.Context = chat;
                if (DBHelper.createInstance().sendChat(chatInfo))
                {
                    //Response.Write("發言成功!");
                    Response.Write("歡迎 " + name + "<br/><br/><br/>");
                    Response.Write("<input id='userName' type='hidden' value=" + name + " />");
                    foreach (ChatInfo demo in DBHelper.createInstance().GetAllInfo())
                    {
                        Response.Write(demo.ToString() + "<br/>");
                    }

                    Response.Write("<input id='txtChat' type='text' /><input id='btnSend' type='button' value='發言' onclick='sendDemo();' />");
                }
                else
                {
                    Response.Write("發言失敗!");
                }

            }
        }
    }


 public partial class WebChat : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string name = Request["name"];
                string pwd = Request["pwd"];
                Userinfo user = new Userinfo();
                user.Name = name;
                user.Pwd = pwd;
                if (DBHelper.createInstance().checkLogin(user))
                {
                    Response.Write("歡迎 " + name + "<br/><br/><br/>");
                    Response.Write("<input id='userName' type='hidden' value=" + name + " />");
                    foreach (ChatInfo chat in DBHelper.createInstance().GetAllInfo())
                    {
                        Response.Write(chat.ToString() + "<br/>");
                    }
                    Response.Write("<input id='txtChat' type='text' /><input id='btnSend' type='button' value='發言' onclick='sendDemo();' />");
                }
                else
                {
                    Response.Write("用戶名或密碼錯誤!");
                }
            }
        }
    }



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章