许多程序员在做业务开发时往往会在服务器端做用户信息的验证,有没有考虑过用jquery的ajax方法来验证登陆呢?且效果比在服务器端写代码来验证好的多,页面无刷新即可实现实现登陆验证,代码也简单。
现在下面贴出来的是很简单的用jquery的ajax方法来验证登陆的代码,适合刚接触jquery的朋友学习。
前台页面代码:
<head>
<script src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
userlogin=function(){
$.ajax({
type:"get",
cache:false,
url:"ajaxpage.aspx",
dataType:"json",
data:"username="+$("#txt_username").val()+"&password="+$("#txt_pwd").val(),
success:function(data){
if(data.sta==1)
{
alert(data.info);
}
else
{
alert(data.info);
}
}
})
}
</script>
</head>
<body>
<div>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="用户名:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txt_username" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblpwd" runat="server" Text="密码:"></asp:Label>
</td>
<td>
<asp:TextBox ID="txt_pwd" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<input id="Button1" type="button" value="登陆" οnclick="userlogin()" /></td>
</tr>
</table>
</div>
</body>
页面类代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//如果用的是get传值,则用Request.QueryString接收参数,如果是post方法传值,则用Request.Params[""]来接收参数
string username=Request.QueryString["username"];
string pwd=Request.QueryString["password"];
//string username=Request.Params["username"];
//string pwd = Request.Params["password"];
result(username, pwd);
}
}
protected void result(string username, string password)
{
JsonClass jc = null;
if (username == "yht" && password == "yht")
{
jc = new JsonClass("登陆成功!", "", 1);
}
else
{
jc = new JsonClass("登陆失败!", "", 0);
}
Response.Clear();
Response.ContentType = "application/json";
//输出带有JSON格式的数据
Response.Write(jc);
//发送JSON格式的数据到客户端并终止该页的执行
//注意这个方法必须有否则会出错
Response.End();
}
JsonClass类代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
/// <summary>
/// JsonClass 的摘要说明
/// </summary>
public class JsonClass
{
public JsonClass(string info,string data,int sta)
{
//
// TODO: 在此处添加构造函数逻辑
//
this.info = info;
this.data = data;
this.sta = sta;
}
private string info;
public string Info
{
get { return info; }
set { info = value; }
}
private string data;
public string Data
{
get { return data; }
set { data = value; }
}
private int sta;
public int Sta
{
get { return sta; }
set { sta = value; }
}
//重写ToString()方法,以便输出格式是标准的JSON格式
public override string ToString()
{
return "{/"data/":/"" + data + "/",/"info/":/"" + info + "/",/"sta/":" + sta + "}";
}
}