C#实现AJAX异步登陆[代码分享]-ASP.NET
在ASP.NET中实现AJAX无刷新登陆教程。IBC会员@璨淼☆星博 提出的教程
首先 : 我们创建一个一般处理程序,命名为:User.ashx,内部代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// User 的摘要说明
/// </summary>
public class User : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string name = context.Request.QueryString["name"].ToString();
string pwd = context.Request.QueryString["pwd"].ToString();
string mes = "";
if (name == "admin" && pwd == "123456")
{
mes = "true";
}
else
{
mes = "false";
}
context.Response.ContentType = "text/plain";
context.Response.Write(mes);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
第二步:Default.aspx页面代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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></title>
</head>
<script type="text/javascript">
function login_onclick() {
var name = document.getElementById("name").value;
var pass = document.getElementById("pass").value;
var url = "User.ashx?name="+name+"&pwd="+pass;
//定义全局xhr
var xhr;
if (window.ActivexObject) {
xhr = new ActivexObjext("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var dom = xhr.responseText;
if (dom == "true") {
alert('成功');
} else {
alert('失败');
}
}
}
xhr.open("GET", url, true);
xhr.send(null);
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="用户名:"></asp:Label>
<asp:TextBox ID="name" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="密码:"></asp:Label>
<asp:TextBox ID="pass" runat="server"></asp:TextBox>
<br />
<input type=button value='登陆'/>
</div>
</form>
</body>
</html>
到这简单的无刷新登陆,就完成了。
需要注意的代码:
<script type="text/javascript">
function login_onclick() {
var name = document.getElementById("name").value;
var pass = document.getElementById("pass").value;
var url = "User.ashx?name="+name+"&pwd="+pass;
//定义全局xhr
var xhr;
if (window.ActivexObject) {
xhr = new ActivexObjext("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var dom = xhr.responseText;
if (dom == "true") {
alert('成功');
} else {
alert('失败');
}
}
}
xhr.open("GET", url, true);
xhr.send(null);
}
</script>
这个原理很简单,就是把用户名跟密码发送给一般处理程序,一般处理程序响应给ajax结果,在script中,得到结果以后进行处理。
要提出的教程访问:
http://www.ibcibc.com/thread-3310-2-1.html
要提出的问题访问:
http://www.ibcibc.com/forum-40-1.html
;P不错
页:
[1]