<script>
$(function () {
$("#btn").click(function () {
var UserName=$("#UserName").val();
var UserPwd = $("#UserPwd").val();
if (UserName == "" || UserPwd == "") {
alert("用户名或密码不能为空!");
}
else {
$.get("LoginHandler.ashx", { "UserName": UserName, "UserPwd": UserPwd }, function (data) {
if (data == "ok") {
window.location.href = "main.html";
}
else {
alert(data);
}
})
}
})
})
</script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<script>
window.onload = function () {
function myAjax(httpMethod, url, callback) {
//发送异步请求
var xhr = new XMLHttpRequest();
xhr.open(httpMethod, url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
}
var btnLogin = document.getElementById("btn").onclick = function () {
var UserName = document.getElementById("UserName").value;
var UserPwd = document.getElementById("UserPwd").value;
if (UserName == "" || UserPwd == "") {
alert("用户名或密码不能为空");
}
else {
var xhr = new XMLHttpRequest();
var strUrl = "LoginHandler.ashx?UserName=" + UserName + "&&UserPwd=" + UserPwd;
////提交后台进行处理
//xhr.open("Get", strUrl,true);
////使用send方法发送请求
//xhr.send();
//xhr.onreadystatechange = function () {
// if (xhr.readyState == 4 && xhr.status == 200) {
// if (xhr.responseText == "ok") {
// window.location.href = "main.html";
// }
// else {
// alert(xhr.responseText);
// }
// }
//}
myAjax("get",strUrl,function(data){
if (data == "ok") {
window.location.href = "main.html";
}
else {
alert(data);
}
})
}
}
}
</script>
</head>
<body>
用户名:<input type="text" name="UserName" id="UserName" />
<br />
密 码:<input type="password" name="UserPwd" id="UserPwd" />
<br />
<input type="button" value="登录" id="btn" />
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace AJAX
{
/// <summary>
/// LoginHandler 的摘要说明
/// </summary>
public class LoginHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string UserName = context.Request["UserName"];
string UserPwd = context.Request["UserPwd"];
string sql = "select count(*) from Users where UserName=@u and Pwd=@p" ;
SqlParameter[] p = { new SqlParameter("@u",UserName),
new SqlParameter("@p",UserPwd),};
int i = Convert.ToInt32(SQLHelper.ExecuteScalar(sql,p));
if (i == 1)
{
context.Response.Write("ok");
}
else
{
context.Response.Write("用户名或密码错误");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}