Ajax的基本元素:
Asynchronous(异步的) JavaScript And Xml
ASP.NET服务器端可以是普通的aspx页面,也可以是一般处理程序(HttpHandler),还可以是Web Service。
一、实现服务器端的程序
首先添加一个aspx页面,手动清除前台页面中的所有HTML标记,最后只保留第一行代码(@Page指令)如下所示:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserExists.aspx.cs" Inherits="UserExists" %>
本页面的后台代码(服务器端)都在Page_Load方法中实现:
protected void Page_Load(object sender, EventArgs e)
{
//输出的格式为文本格式
Response.ContentType = "text/plain";
if (Request.QueryString["loginId"] != null)
{
//接受客户端发送的“用户名”数据
string loginId = Request.QueryString["loginId"].Trim().ToString();
if (loginId.Length > 0)
{
//根据“用户名”判断用户是否存在
if (UserManager.GetById(loginId))
{
Response.Write("true");
}
else
{
Response.Write("false");
}
}
else
{
Response.Write("false");
}
}
else
{
Response.Write("false");
}
}
二、实现Ajax客户端
javascript代码:
//创建XMLHttpRequest对象
function createXMLHttpRequest()
{
if (window.ActiveXObject) {//如果是IE浏览器
return new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {//非IE浏览器
return new XMLHttpRequest();
}
}
//编写函数实现对服务器端的访问
var xhr;//声明一个全局变量
function userExists(loginId)
{
if (loginId != "") {
//请求字符串
var url = "UserExists.aspx?loginId=" + loginId;
//1.创建XMLHttpRequest
xhr = createXMLHttpRequest();
//2.设置回调函数
xhr.onreadystatechange = readyDo;
//3.初始化XMLHttpRequest组件
xhr.open(
"GET",//提交方式(通常是GET或POST)
url, //目标资源URL的字符串
true //指示请求是否是异步的
);
//4.发送请求
xhr.send(null);
}
}
//实现回调函数从XMLHttpRequest对象中获取返回数据并进行处理
function readyDo()
{
if (xhr.readyState==4 && xhr.status==200) {
var result = xhr.responseText;
//对返回结果进行处理
if (result == "true")
{
//mess_double为HTML文档中定义的span元素的id,显示提示信息
document.getElementById("mess_double").innerHTML = "该用户名已被注册,请重新输入!";
document.getElementById("mess_double").style.color = "Red";
document.getElementById("mess_double").style.display = "inline";
}
else
{
document.getElementById("mess_double").innerHTML = "该用户名可用!";
document.getElementById("mess_double").style.color = "Green";
document.getElementById("mess_double").style.display = "inline";
}
}
}
html代码:
<label>用户名</label>
<asp:TextBox CssClass="opt_input" ID="txtLoginId" runat="server" οnblur="userExists(this.value)"></asp:TextBox>
<asp:RequiredFieldValidator ID="valrLoginId" runat="server" ErrorMessage="请输入用户名" ControlToValidate="txtLoginId">*</asp:RequiredFieldValidator>
<span id="mess_double" style="display:none;"></span>