前台文件代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ajaxtest.aspx.cs" Inherits="ajaxtest" %>
<!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 runat="server">
<title>Ajax-Test</title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(function () {
$("#BtnLogin").click(function () {
var name = $("#Name").val()
var pwd = $("#Pwd").val();
$.ajax({
url: "DoAjax.ashx",
data: { name: name , pwd: pwd },
type: "post",
success: function (msg) {
alert(msg);
}
})
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>用户名:<input id="Name" type="text" /></p>
<p>密 码:<input id="Pwd" type="text" /></p>
<input id="BtnLogin" type="button" value="登录"/>
</div>
</form>
</body>
</html>
DoAjax.ashx文件代码如下:
<%@ WebHandler Language="C#" Class="DoAjax" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;
public class DoAjax : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string name = context.Request.Params["name"].ToString();
string pwd = context.Request.Params["pwd"].ToString();
string constr = @"server=.\sqlexpress;database=Exam;uid=zzz;pwd=123";
using (SqlConnection scon = new SqlConnection(constr))
{
scon.Open();
SqlCommand scmd = new SqlCommand("UserLogin", scon);
scmd.CommandType = CommandType.StoredProcedure; //设置为存储过程
SqlParameter[] param = new SqlParameter[] { //创建参数数组
new SqlParameter("@UserID",name),
new SqlParameter("@UserPwd",pwd),
new SqlParameter("@record",SqlDbType.TinyInt)
};
param[2].Direction = ParameterDirection.Output; //设置输出参数
scmd.Parameters.AddRange(param);
scmd.ExecuteScalar();
if (Convert.ToInt32(param[2].Value) > 0) //接收输出参数 并转化判断
{
context.Response.Write("登录成功!");
}
else
{
context.Response.Write("登录失败!");
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
存储过程代码如下:
CREATE procedure UserLogin
(
--用户名
@UserID varchar(50),
--密码
@UserPwd varchar(50),
--验证结果 正确返回1 不正确返回0
@record tinyint output
)
as
begin
--在用户表中验证用户名和密码
if exists(select * from test where id=@UserID and pwd=@UserPwd)
--正确为1
set @record=1
else
--不正确为0
set @record=0
end