一款经典的ajax登录页面 后台asp.net_AJAX相关

下面实现一个经典的登录页面,有保存密码功能,页面上所有的控件都是html控件,没有服务器控件

1,新建一名为login.htm的静态网页文件,作为登录页面,如图

body标签代码

复制代码 代码如下:

<body onkeydown ="enterLogin()"> <!--添加按下键盘事件-->

<div style="text-align: center">
<table border="1" cellpadding="1">
<tr>
<td align="center" style="width: 100px; height: 20px; background-color: #99cccc"
valign="middle">
用户名:</td>
<td align="center" style="width: 74px; height: 20px; background-color: #99cccc" valign="middle">
<input id="txtusername" style="width: 111px; height: 19px" type="text" onblur ="checkuser()" /></td>
<td align="center" style="width: 199px; height: 20px; background-color: #99cccc"
valign="middle"><img src="" id ="imgCheck" style = "visibility :hidden; "/ ><span id ="unMessage">
</span></td>
</tr>
<tr>
<td align="center" style="width: 100px; height: 29px; background-color: #99cccc"
valign="middle">
密码:</td>
<td align="center" style="width: 74px; height: 29px; background-color: #99cccc" valign="middle">
<input id="txtpwd" style="width: 107px; height: 17px" type="password" /></td>
<td align="center" style="width: 199px; height: 29px; background-color: #99cccc"
valign="middle"><span id ="pwdMessage"></span>
</td>
</tr>
<tr>
<td align="center" colspan="3" style="background-color: #99cccc" valign="middle">
<input id="cbRememberPwd" type="checkbox" />记住密码一个月</td>
</tr>
<tr>
<td align="center" colspan="3" style="background-color: #99cccc" valign="middle">
<input id="btnOK" type="button" value="登录" onclick ="login()" />
<input id="btnReset" type="button" value="重置" onclick ="reset()" /></td>
</tr>
</table>
</div>

</body>

2,在login.htm中引入外部js代码

<script type ="text/javascript" src ="aj.js" ></script>
<script type ="text/javascript" src ="loginCookies.js" ></script>

其中aj.js为ajax封装的类,loginCookie.js为对Cookie操作的代码

aj.js代码如下

//JScript文件

//ajax请求功能函数
//作者:吴宝佑
//get调用方式:(1)实例化 var aj=new ajax(); (2)调用get函数 aj.get(url,callback) (3)写回调函数 function callback(xhr){xhr.responsetext}
//post调用方式:(1)实例化 var aj=new ajax(); (2)调用post函数 aj.post(url,content,callback) (3)写回调函数 function callback(xhr){xhr.responsetext}

//构造ajax对象

function ajax() 
{
    function getXHR()//获取xmlhttprequest
    {
        var request=false;
        try 
        {
            request = new XMLHttpRequest();
        } 
        catch (trymicrosoft) 
        {
              try 
              {
                request = new ActiveXObject("Msxml2.XMLHTTP");
              } 
              catch (othermicrosoft) 
              {
                try 
                {
                      request = new ActiveXObject("Microsoft.XMLHTTP");
                } 
                catch (failed) 
                {
                      request = false;
                }
              }
        }
        return request;
    }

    this.get = function (openUrl,successFun)//ajax对象的get方法,通过get方式发送请求,openUrl为请求的页面,successFun为成功回调执行的函数
    {
        var request = getXHR();
        request.open("get",openUrl,true);
//        request.onreadystatechange = function ()
//        {
//            if (request.readystate==4)
//            {
//                if (request.status==200)
//                {
//                    successFun(request);
//                }
//            }
//        };
        request.onreadystatechange = update;
        function update()
        {
            if (request.readystate==4)
            {
                if (request.status==200)
                {
                    successFun(request);
                }
            }
        }
        request.send(null);
    }

    this.post = function (openUrl,sendContent,successFun)//ajax对象的post方法,通过post方式发送请求,openUrl为请求的页面,successFun为成功回调执行的函数
    {
        var request = getXHR();
        request.open("post",openUrl,true);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//告诉服务器发送的是文本
        request.onreadystatechange = update;
        function update()
        {
            if (request.readystate==4)
            {
                if (request.status==200)
                {
                    successFun(request);
                }
            }
        }
        request.send(sendContent);
    }
}

loginCookie.js代码如下

//JScript文件

//SetCookie 保存一个Cookie。参数中除了name和value以外,其他可以省略。
//GetCookie 通过一个Cookie的名字取出它的值。
//DelCookie 删除一个Cookie,也就是让一个Cookie立刻过期。参数中除了name,其他可以省略。

//测试
//SetCookie("username", "123");expires代表"月"
//alert(GetCookie("username"));
//DelCookie("username");
//alert(GetCookie("username"));

function SetCookie(name, value, expires, path, domain, secure) {
  var today = new Date();
  today.setTime(today.getTime());
  if(expires) { expires *= 2592000; }
  var expires_date = new Date(today.getTime() + (expires));
  document.cookie = name + "=" + escape(value)
    + (expires ? ";expires=" + expires_date.toGMTString() : "")
    + (path ? ";path=" + path : "")
    + (domain ? ";domain=" + domain : "")
    + (secure ? ";secure" : "");
}

function GetCookie(name) {
  var cookies = document.cookie.split( ';' );
  var cookie = '';

  for(var i=0; i<cookies.length; i++) {
    cookie = cookies[i].split('=');
    if(cookie[0].replace(/^\s+|\s+$/g, '') == name) {
      return (cookie.length <= 1) ? "" : unescape(cookie[1].replace(/^\s+|\s+$/g, ''));
    }
  }
  return null;
}

function Delcookie(name, path, domain) {
  document.cookie = name + "="
    + (path ? ";path=" + path : "")
    + (domain ? ";domain=" + domain : "")
    + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

3,写login.htm页面中的js代码,放在head标签之间

    <script type ="text/javascript" >
        window.onload = function (){
            document.getElementById ('txtusername').focus();//用户名框获得焦点

            if (GetCookie('user_name') != null && GetCookie('user_pwd') != null)//设置记住密码的登录页面
            {
                document.getElementById ("txtusername").value = GetCookie('user_name');
                document.getElementById ("txtpwd").value = GetCookie('user_pwd');
            }
        }

        String.prototype.Trim = function() //自定义的去除字符串两边空格的方法
        { 
            return this.replace(/(^\s*)|(\s*$)/g, ""); 
        } 

        function checkuser()//检验用户名是否正确
        {
            var img = document.getElementById ("imgCheck")
            img.src="iamges/blue-loading.gif";//设置图片及其可见性
            img.style.visibility = "visible";

            var aj = new ajax();//以下为ajax请求
            var username = document.getElementById ("txtusername").value.Trim();
            var url = "login.aspx?uname="+escape(username);
            aj.get(url,callback);
            function callback(obj)
            {
                var response = obj.responsetext;
                var res = response.split('\n');
                if (res[0] == "ok")
                {
                    img.src="iamges/icon-info.gif";
                    document.getElementById ("unMessage").innerHTML = "<font color='#00ff00'>用户名正确</font>";
                }
                else
                {
                    img.src="iamges/icon-warning.gif";
                    document.getElementById ("unMessage").innerHTML = "<font color='#ff0000'>用户名错误</font>";
                }
            }
        }

        
        function login()//登录
        {
            if (document.getElementById ("unMessage").innerText == "用户名错误")
            {
                alert("你的用户名错误");
            }
            else if (document.getElementById ("txtpwd").value == "")
            {
                alert("请输入密码");
            }
            else
            {
                var aj = new ajax();
                var username = document.getElementById ("txtusername").value.Trim();
                var userpwd = document.getElementById ("txtpwd").value;
                var url = "login.aspx?name="+escape(username)+"&pwd="+escape(userpwd);
                aj.get(url,callback);
                function callback(obj)
                {
                    var response = obj.responsetext;
                    var res = response.split('\n');
                    if (res[0] == "ok")
                    {
                        if (document.getElementById ("cbRememberPwd").checked)
                        {
                            SetCookie('user_name',username,1);//保存密码一个月
                            SetCookie('user_pwd',userpwd,1);
                        }
                        else
                        {
                            SetCookie('user_name',username);
                            SetCookie('user_pwd',userpwd);
                        }
                        window.open ("loginIndex.htm","_self");
                    }
                    else
            &p;            {
                        alert("密码错误");
                    }
                }
            }
        }

        function reset()//重置
        {
            window.onload();//执行窗体登录事件
            document.getElementById ("txtusername").value="";
            document.getElementById ("txtpwd").value="";
        }

        function enterLogin()
        {
            if (event.keyCode==13) //如果按下的是Enter键的话,就执行登录语句
            {
                login();
            }
        }
    </script>

4,新建一名为login.aspx的页面,该页面作为ajax请求的页面,login.aspx.cs代码如下

    protected void Page_Load(object sender, EventArgs e)
    {
        OleDbConnection Conn = DBcon.get_con();

        if (Request["uname"] != null)
        {
            string username = Request["uname"].ToString();
            string strSql = "select * from [user] where u_name='" + username + "'";
            Conn.Open();
            OleDbCommand Comd = new OleDbCommand(strSql, Conn);
            OleDbDataReader dr = Comd.ExecuteReader();
            if (dr.Read())
            {
                Response.Write("ok\n");
            }
            else
            {
                Response.Write("fail\n");
            }
            //if (Comd.ExecuteNonQuery() > 0)
            //{
            //    Response.Write("存在这个用户\n");
            //}
            //else
            //{
            //    Response.Write("没有此用户名\n");
            //}
            Conn.Close();
        }

        if (Request["name"] != null && Request["pwd"] != null)
        {
            string name = Request["name"].ToString();
            string pwd = Request["pwd"].ToString();
            string strSql = "select * from [user] where u_name='" + name + "'" + " and u_pwd='" + pwd + "'";
            Conn.Open();
            OleDbCommand Comd = new OleDbCommand(strSql, Conn);
            OleDbDataReader dr = Comd.ExecuteReader();
            if (dr.Read())
            {
                Response.Write("ok\n");
            }
            else
            {
                Response.Write("fail\n");
            }
        }
    }

5,新建一名为loginIndex.htm的静态页面,作为用户登录之后的首页

其body标签代码如下

<body>
    <span id ="username"> </span>
</body>

6,在loginIndex.htm页面引入loginCookie.js文件

<script type ="text/javascript" src ="loginCookies.js" ></script>

7,写loginIdex.htm页面的js代码,放在head标签之间

    <script type ="text/javascript" >
        window.onload = function ()
        {
            if(GetCookie('user_name')==null || GetCookie('user_pwd')==null)//如果没有登录,而是直接在网页中输入网址的
            {
                alert('你还没有登录!\n返回到登陆页面。');
                window.navigate("login.htm");
            }
            else
            {
                var uname = GetCookie('user_name');
                document.getElementById ('username').innerHTML ="欢迎你: " + uname + "     <a href='#' onclick = 'off()'>注销</a>";//提供"注销"按钮
            }
        }

        function off()//注销事件
        {
            if (window.confirm("你真要注销吗?"))
            {
                Delcookie("user_name");
                Delcookie("user_pwd");
                window.navigate("login.htm");
            }
        }
    </script>

8,完成,客户端代码较多,但是交互性很好

演示如下:

当输入完用户名,鼠标光标离开用户名框之后,系统会快速检验用户名是否合法

进入首页后,出现的窗口,带有当前登录的用户和注销按钮

当用户点击注销按钮时,会友情提示你是否真的注销

当你不是输入用户和密码登陆,也是直接在浏览器地址栏中输入首页网址的时候,系统会提示你没有登录,并直接返回到登陆页面。

当用户输入了有效的用户名和密码,并要求系统记住密码,用户下次进入到登录页面时,系统会把上次记住的用户名和密码显示在输入框中。。

并且这个时候直接在浏览器的地址栏中输入首页地址,也是能正常访问的。

nbsp;       {
                        alert("密码错误");
                    }
                }
            }
        }

        function reset()//重置
        {
            window.onload();//执行窗体登录事件
            document.getElementById ("txtusername").value="";
            document.getElementById ("txtpwd").value="";
        }

        function enterLogin()
        {
            if (event.keyCode==13) //如果按下的是Enter键的话,就执行登录语句
            {
                login();
            }
        }
    </script>

4,新建一名为login.aspx的页面,该页面作为ajax请求的页面,login.aspx.cs代码如下

    protected void Page_Load(object sender, EventArgs e)
    {
        OleDbConnection Conn = DBcon.get_con();

        if (Request["uname"] != null)
        {
            string username = Request["uname"].ToString();
            string strSql = "select * from [user] where u_name='" + username + "'";
            Conn.Open();
            OleDbCommand Comd = new OleDbCommand(strSql, Conn);
            OleDbDataReader dr = Comd.ExecuteReader();
            if (dr.Read())
            {
                Response.Write("ok\n");
            }
            else
            {
                Response.Write("fail\n");
            }
            //if (Comd.ExecuteNonQuery() > 0)
            //{
            //    Response.Write("存在这个用户\n");
            //}
            //else
            //{
            //    Response.Write("没有此用户名\n");
            //}
            Conn.Close();
        }

        if (Request["name"] != null && Request["pwd"] != null)
        {
            string name = Request["name"].ToString();
            string pwd = Request["pwd"].ToString();
            string strSql = "select * from [user] where u_name='" + name + "'" + " and u_pwd='" + pwd + "'";
            Conn.Open();
            OleDbCommand Comd = new OleDbCommand(strSql, Conn);
            OleDbDataReader dr = Comd.ExecuteReader();
            if (dr.Read())
            {
                Response.Write("ok\n");
            }
            else
            {
                Response.Write("fail\n");
            }
        }
    }

5,新建一名为loginIndex.htm的静态页面,作为用户登录之后的首页

其body标签代码如下

<body>
    <span id ="username"> </span>
</body>

6,在loginIndex.htm页面引入loginCookie.js文件

<script type ="text/javascript" src ="loginCookies.js" ></script>

7,写loginIdex.htm页面的js代码,放在head标签之间

    <script type ="text/javascript" >
        window.onload = function ()
        {
            if(GetCookie('user_name')==null || GetCookie('user_pwd')==null)//如果没有登录,而是直接在网页中输入网址的
            {
                alert('你还没有登录!\n返回到登陆页面。');
                window.navigate("login.htm");
            }
            else
            {
                var uname = GetCookie('user_name');
                document.getElementById ('username').innerHTML ="欢迎你: " + uname + "     <a href='#' onclick = 'off()'>注销</a>";//提供"注销"按钮
            }
        }

        function off()//注销事件
        {
            if (window.confirm("你真要注销吗?"))
            {
                Delcookie("user_name");
                Delcookie("user_pwd");
                window.navigate("login.htm");
            }
        }
    </script>

8,完成,客户端代码较多,但是交互性很好

演示如下:

当输入完用户名,鼠标光标离开用户名框之后,系统会快速检验用户名是否合法

进入首页后,出现的窗口,带有当前登录的用户和注销按钮

当用户点击注销按钮时,会友情提示你是否真的注销

当你不是输入用户和密码登陆,也是直接在浏览器地址栏中输入首页网址的时候,系统会提示你没有登录,并直接返回到登陆页面。

当用户输入了有效的用户名和密码,并要求系统记住密码,用户下次进入到登录页面时,系统会把上次记住的用户名和密码显示在输入框中。。

并且这个时候直接在浏览器的地址栏中输入首页地址,也是能正常访问的。

时间: 2024-08-31 05:59:43

一款经典的ajax登录页面 后台asp.net_AJAX相关的相关文章

一款经典的ajax登录页面 后台asp.net

下面实现一个经典的登录页面,有保存密码功能,页面上所有的控件都是html控件,没有服务器控件 1,新建一名为login.htm的静态网页文件,作为登录页面,如图 body标签代码 复制代码 代码如下: <body onkeydown ="enterLogin()"> <!--添加按下键盘事件--> <div style="text-align: center"> <table border="1" cel

jQuery AJAX实现调用页面后台方法_AJAX相关

本文实例为大家分享了jQuery AJAX调用页面后台方法,供大家参考,具体内容如下 1.新建demo.aspx页面. 2.首先在该页面的后台文件demos.aspx.cs中添加引用. using System.Web.Services; 1).无参数的方法调用. 大家注意了,这个版本不能低于.net framework 2.0.2.0已下不支持的. 后台代码: [WebMethod] public static string SayHello() { return "Hello Ajax!&q

Ajax Session失效跳转登录页面的方法_AJAX相关

在Struts应用中,我们发出的请求都会经过 相应的拦截器进行相关处理,一般都会有一个用户登录拦截(Session失效拦截):一般请求的话,如果Session失效时,我们会跳到登录页面,可是如果我们采用AJAX请求时,将会返回登录页面的HTML代码,这肯定不是我们想要的,那么我们如何解决呢?请看以下步骤: 一.建立拦截器 package com.xxx.planeap.interceptor; import javax.servlet.http.HttpServletRequest; impor

jQuery AJAX实现调用页面后台方法

本文实例为大家分享了jQuery AJAX调用页面后台方法,供大家参考,具体内容如下 1.新建demo.aspx页面. 2.首先在该页面的后台文件demos.aspx.cs中添加引用. using System.Web.Services; 1).无参数的方法调用. 大家注意了,这个版本不能低于.net framework 2.0.2.0已下不支持的. 后台代码: [WebMethod] public static string SayHello() { return "Hello Ajax!&q

ajax的异步请求-用AJAX实现页面部分刷新,无法实现

问题描述 用AJAX实现页面部分刷新,无法实现 function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

登录超时给出提示跳到登录页面(ajax、导入、导出)_AJAX相关

一.一般页面登录超时验证,可以用过滤器filter,如下: package com.lg.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequ

使用Jquery搭建最佳用户体验的登录页面之记住密码自动登录功能(含后台代码)_jquery

需要引入插件jquery.md5.js 可直接在IIS下运行: 用户名:Ethan.zhu 密 码:123456789 完整文件下载:WebApplication1_jb51.rar 首先将按钮单击事件的异步验证提取出来作为一个单独的函数,需要将按钮单击事件里面的变量提取出来定义为全局变量,并且增加一个变量editPass(用来标记是自己输入密码,还是从cookies中读取的密码) 复制代码 代码如下: var wrongTypeName, //用户名的错误类型,可以直接作为错误提示信息数组的下

ajax+eclipse+jsp页面后台是java

问题描述 ajax+eclipse+jsp页面后台是java 我想知道怎么用ajax分页,每页10条,ajax写好之后,后台写什么方法去执行调用,我是新手,不懂这些,求大神帮帮忙 我用的是spring,springmvc+hibernate,三个框架,实在是不会了. <script type="text/javascript"> $(function() { //此demo通过Ajax加载分页元素 var initPagination = function() { var

jquery ajax方法调用在session超时以后如何跳转到登录页面?

问题描述 jquery ajax方法调用在session超时以后如何跳转到登录页面?session超时以后虽然被过滤器过滤到了,但是并不会跳转到登录页面请求具体的解决方法.我参考了这篇文章,但是我调用ajaxStart不起作用.http://www.blogjava.net/vickzhu/archive/2009/06/05/280223.htmlext jquery 用户访问超时(ext session过期) 解决两种情况下的用户访问超时.a)普通http请求的session超时.b)异步h