Ajax无刷新登录举例
前台页面:Login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>用户登录</title> <script src="Common.js" type="text/javascript"></script> <style type="text/css"> #Logtab{ margin:auto} </style> <script type="text/javascript"> //验证用户名、密码是否为空 function validate(strN, strP) { if (strN == "") { document.getElementById("txtName").focus(); alert("用户名不能为空!"); } else if (strP == "") { document.getElementById("txtPwd").focus(); alert("密码不能为空!"); } else { return true; } return false; } function doLoginByPost() { var strName = document.getElementById("txtName").value; var strPwd = document.getElementById("txtPwd").value; if (validate(strName, strPwd) == true) { var xhr = createXhr(); xhr.open("POST", "LoginAjax.ashx", true); //POST方式 设置报文头 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { //判断服务器返回的状态码是否为200,如果不是,则可能服务器出现了不测 if (xhr.status == 200) { var res = xhr.responseText; //获得服务器输出的字符串 if (res == "err") { alert("对不起,您的用户名或密码为空了........... : )"); } else if (res == "ok") { alert("恭喜您,登录成功啦!........... : )"); window.location = "index.aspx"; } else if (res == "no") { alert("对不起,您的用户名或密码错误了........... : )"); } } else { alert("对不起,服务器繁忙,请稍后再试~~~"); } } } //发送用户名密码 xhr.send("txtName=" + strName + "&txtpwd=" + strPwd); } } window.onload = function () { document.getElementById("btnlogin").onclick = doLoginByPost; } </script> </head> <body> <form action=""> <table id="Logtab"> <tr><td colspan="2" align="center">用户登录</td></tr> <tr><td >用户名</td><td><input type="text" name="txtName" id="txtName"/></td></tr> <tr><td>密码</td><td><input type="password" name="txtPwd" id="txtPwd"/></td></tr> <tr><td colspan="2" align="center"><input id="btnlogin" type="button" value="登录" onclick="return btnlogin_onclick()" /> <input type="button" value="取消" /></td></tr> </table> </form> </body> </html>
后台页面:AjaxLogin.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace AjaxLogin
{
/// <summary>
/// LoginAjax 的摘要说明
/// </summary>
public class LoginAjax : IHttpHandler,IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string strName = context.Request.Form["txtName"];
string strPwd = context.Request.Form["txtpwd"];
if (string.IsNullOrEmpty(strName) || string.IsNullOrEmpty(strPwd))
{
context.Response.Write("err");
}
else
{
if (strName == "liu" && strPwd == "123")
{
context.Session["un"] = strName;
context.Response.Write("ok");
}
else
{
context.Response.Write("no");
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
2013-08-27 21:54:09

浙公网安备 33010602011771号