2015-11-06 ajax

一:登录页面.html

制作登录页面html后缀,是客户端控件,不能直接和后台交互,而服务端aspx可以和后台交互,所以要通过js获得内容,通过aspx和后台交互

前台:

<body>
    <table>
        <tr><td>用户名:</td><td><input type="text" id="txtUserName" /></td></tr>
        <tr><td>密码:</td><td><input type="password" id="txtPwd" /></td></tr>
        <tr><td><input type="button" id="btnLogin"  value="登录"/></td></tr>
    </table>
</body>

在js中

$(function () {
    $("#btnLogin").click(function () {
        var username = $.trim($("#txtUserName").val());
        var pwd = $.trim($("#txtPwd").val());
        if (username == "" || pwd == "") {
            alert("用户名或密码不能为空");
        }
        else {  //放ajax
            $.post("/ajax/LoginAjax.ashx?cmd=login", { "username": username, "pwd": pwd }, function (data) {     //json格式
                var data = eval('(' + data + ')');//吧json转成js数组
                if (data.Success) {
                    alert(data.Infor);
                }
                else {
                    alert(data.Infor);
                }

              //////alert(data)               //这是一种数据返回方式字符串格式(弹出返回的所有数据),服务端一般返回的是json格式
            });
        }
    });

一般应用程序ashx中

 Dictionary<string, object> dt = new Dictionary<string, object>();     //字典集合 key存string value存object格式

 JavaScriptSerializer jss = new JavaScriptSerializer();                         //把dt转换为json格式

 ①public void ProcessRequest(HttpContext context)        

{            

           string username = context.Request.Form["username"].ToString();
            string pwd = context.Request.Form["pwd"].ToString();
            string strSql = "select UserId from UserInfor where UserName=@UserName and Pwd=@Pwd";
            SqlParameter[] para = new SqlParameter[] { new SqlParameter("@UserName", SqlDbType.NVarChar, 50),

                                                                              new SqlParameter("@Pwd", SqlDbType.NVarChar, 50) };
            para[0].Value = username;
            para[1].Value = pwd;
            if (SqlHelper.Exists(strSql, para))//判断sql语句里面的结果是否存在
            {

                ////////context.Response.Write("登录成功")
                dt.Add("Success", true);
                dt.Add("Infor", "登录成功");
            }
            else
            {

                ////////context.Response.Write("用户名密码错误")
                dt.Add("Success", false);
                dt.Add("Infor", "登录失败");
            }
           context.Response.Write( return jss.Serialize(dt));

 }

二:搜索例子

 <head>    

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    

<title></title>    

<script src="js/jquery-1.10.2.min.js"></script>    

<script src="js/Login.js"></script>    

<style type="text/css">        

  #txtSel {             width: 300px;             height: 20px;         }

    #dcon {             width: 300px;             border: solid 1px #ccc;             display: none;         }

#dcon ul {                 list-style-type: none;                 padding: 0px;                 margin: 0px;                 font-family: "微软雅黑";             }    

</style>

</head>

 

<body>    

<input type="text" id="txtSel" />    

<div id="dcon">

</div>

</body>

 js页面:

 $("#txtSel").keyup(function () {      ///手离开键盘的时候,触发的事件
        var title = $.trim($("#txtSel").val());
        if (title == "") {
            $("#dcon").hide();
        }
        else {
            $.post("/ajax/LoginAjax.ashx?cmd=sel", { "title": title }, function (data) {      //////cmd=sel实现在同一个后台中处理多个方法,通过修改下面的ashx
                data = eval('(' + data + ')');                                                                    //////过程是通过传递一个参数,后台接收这个参数进行判断
                if (data.Success) {
                    $("#dcon").show();
                    $("#dcon").html(data.Infor);
                }
                else {
                    $("#dcon").show();
                    $("#dcon").html(data.Infor);
                }
            });
        }
  }); 

后台ashx:

        HttpContext context;        

        Dictionary<string, object> dt = new Dictionary<string, object>();        

        JavaScriptSerializer jss = new JavaScriptSerializer();        

        string strReturn = "";        

        public void ProcessRequest(HttpContext context)        

       {            

            this.context = context;            

            string cmd = context.Request.QueryString["cmd"].ToString();            

            switch (cmd)             {                

            case "login":                    

                              strReturn = Login();                    

                              break;                

            case "sel":                    

                              strReturn = SelTitle();                    

                              break;            

            }            

            context.Response.Write(strReturn);

        }

        public string SelTitle()
        {
            string title = context.Request.Form["title"].ToString();
            string strSql = "select top 10 title from RNews where Title like '%'+@title+'%'";
            SqlParameter[] para = new SqlParameter[] { new SqlParameter("@title", SqlDbType.NVarChar, 50) };
            para[0].Value = title;
            StringBuilder sb = new StringBuilder();
            SqlDataReader read = SqlHelper.ExecuteReader(SqlHelper.connectionString, CommandType.Text, strSql, para);
            if (read.HasRows)
            {
                sb.Append("<ul>");
                while (read.Read())
                {
                    sb.Append(string.Format("<li>{0}</li>", read["title"].ToString()));
                }
                sb.Append("</ul>");
                dt.Add("Success", true);
                dt.Add("Infor", sb.ToString());
            }
            else
            {
                dt.Add("Success", false);
                dt.Add("Infor", "没有数据");
            }
            return jss.Serialize(dt);     ////不定义json(dt.)直接return sb.tostring();也可,在js里直接输出,alert(data)
        }

       将①中代码放入函数Login中

        public string Login()
        {
            string username = context.Request.Form["username"].ToString();
            string pwd = context.Request.Form["pwd"].ToString();
            ...

            ...

            ...
            ...
            else
            {
                dt.Add("Success", false);
                dt.Add("Infor", "登录失败");
            }
            return jss.Serialize(dt);
        }

 三:js中获取cookies

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script src="js/cookies.jquery.js"></script>   //js-cookies插件
    <script type="text/javascript">
        $(function () {
            $("#setCookie").click(function () {
                $.cookie("username", "admin1", { expires: 7, path: "/" });    /// username任意名,保存七天,如果想要保存到小时可以除     7/24=7小时

                                                                         ///path: "/":比如当前文件在一级目录,path的存在是为了能让二级目录,三级目录...都能获取的到
            });
            $("#getCookie").click(function () {
                alert($.cookie("username"));
            });
            $("#reCookie").click(function () {
                $.cookie("username", null);
            });
        });
    </script>
</head>
<body>
    <input type="button" value="存储cookie" id="setCookie" />
    <input type="button" value="获取cookie" id="getCookie" />
    <input type="button" value="清空cookie" id="reCookie" />
</body>
</html>

posted @ 2015-12-11 21:17  以深  阅读(127)  评论(0编辑  收藏  举报
TOP