原理:就是在页面后面偷偷的做东西,通过的媒介为XMLHttpRequest对象,由它来接受和发送请求,那发送给谁呢,发送给Handler.ashx文件,由它来处理,并把结果通过XMLHttpRequest对象返回给页面。
效果:
页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>AJAX演示</title>
<script type="text/javascript">
var xmlHttp;
function CreateXmlHttpRequest()//创建XMLHTTP对象
{
var objXMLHttp=null
if(window.ActiveXObject)
{
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XmlHttpRequest)
{
objXMLHttp = new XmlHttpRequest();
}
return objXMLHttp;
}
function keydown()//接受事件,键盘按下
{
xmlHttp = CreateXmlHttpRequest();
var url = "Handler.ashx";
url = url+ "?a=" + document.getElementById("TextBox1").value;
xmlHttp.open("GET",url,true);//发带参数请求
xmlHttp.onreadystatechange = ShowResut;//状态完成改变则显示结果
xmlHttp.send(null);
}
function ShowResut()//显示结果
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)//请求处理完成
{
document.getElementById("TextBox2").value = xmlHttp.responseText;//通过脚本设置值
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" onkeyup="keydown()"></asp:TextBox><br />
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></form>
</body>
</html>
对应的Handler.ashx
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write(context.Request.Params["a"].ToString().Trim());//返回所接受的参数
}
public bool IsReusable {
get {
return false;
}
}
}