1. 程式人生 > >Jquery之Ajax例項_登入

Jquery之Ajax例項_登入

一、Login.html程式碼

<!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.7.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#msg").css("display","none");
            $("#btnLogin").click(function () {
                userLogin();
            });
        });
        function userLogin() {
            var userName = $("#txtUserName").val();
            var userPwd = $("#txtUserPwd").val();
            if (userName != "" && userPwd != "") {
                $.post("UserLogin.ashx", { "userName": userName, "userPwd": userPwd }, function (data) {
                    var serverData = data.split(':');
                    if (serverData[0] == "ok") {
                        window.location.href = "/2015-5-31/UserInfoList.aspx";
                    } else {
                        $("#msg").css("display", "block");
                        $("#msg").text(serverData[1]);
                        $("#txtUserName").val("");
                    }

                });

            } else {
                $("#msg").css("display", "block");
                $("#msg").text("使用者名稱密碼不能為空!!");
            }
        }
    </script>
</head>
<body>

    使用者名稱:<input type="text" name="txtName" id="txtUserName" />
    密碼:<input type="password" name="txtPWD"  id="txtUserPwd"/><br />
        <input type="button" value="登入" id="btnLogin" />
    <span id="msg" style="font-size:14px;color:red"></span><br />
</body>
</html>
二、UserLogin.ashx.cs程式碼
using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CZBK.ItcastProject.WebApp._2015_6_2
{
    /// <summary>
    /// UserLogin 的摘要說明
    /// </summary>
    public class UserLogin : IHttpHandler,System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string userName = context.Request["userName"];
            string userPwd=context.Request["userPwd"];
            BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
            string msg = string.Empty;
            UserInfo userInfo = null;
            if (UserInfoService.ValidateUserInfo(userName, userPwd, out msg, out userInfo))
            {
                context.Session["userInfo"] = userInfo;
                context.Response.Write("ok:"+msg);
            }
            else
            {
                context.Response.Write("no:" + msg);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}