最近,老聽同事說起Ajax.今天花了一些時間,在網上讀了一些相關帖子,自己試着做了兩個測試程序,搞了一搞.一個是用Ajax.Net這個框架做的,另一個沒用框架. Ajax.Net的Guide已夠詳細,不用贅述.現將沒有框架的例子程序貼到下面.對自己,是備忘.對別人(如果有興趣的話),也不妨瞅上兩眼,知道有Ajax這個東西.Google已經用到了它,在Suggest和Map中.微軟在下一代的Hotmail中也用到了這種技術,據說還將在Asp.Net2.0正式版中加入對它的支持.看樣子,這個技術不可小覷之.不過,看網上的帖子,也有人對其罵之,說七宗罪之類.作爲底層程序員,咱們管不了那麼多,反正俗話說得好,藝不壓身,學點新技術,總之是沒有壞處的.廢說不說了,言歸正傳.
程序是在VS2005Beta2中ASP.Net中做的.
1.新建一個Website,將Default.aspx更名爲Test1.aspx
在Test1.aspx中加入如下代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<!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>Untitled Page</title>
<script language="javascript">
function makeRequest(url)
{
var httpRequest=false;
if(window.XMLHttpRequest)
{
httpRequest=new XMLHttpRequest();
}
else
{
try
{
httpRequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Sorry to can't create the XmlHttp instance within the browser.");
}
}
}
if(httpRequest)
{
httpRequest.onreadystatechange=myCallBack;
httpRequest.open('get',url,true);
httpRequest.send(null);
return true;
}
else
return false;
function myCallBack()
{
if(httpRequest.readyState==4)
{
if(httpRequest.status==200)
{
alert(httpRequest.responseText);
}
else
alert("ResponseText Error!")
}
}
}
function myRequest()
{
var name=document.getElementById("name");
if(!name||name.value==null)
alert("Please input the name first");
else
{
makeRequest("MyHandler2.ashx?name="+name.value)
}
}
</script>
</head>
<body>
<form id="form1">
<div>
<label for="name">Name:</label>
<input type="text" id="name" value="" />
<input type="button" id="button" value="Request" onclick="myRequest()"/>
</div>
</form>
</body>
</html>
2. 新建一個Generic Handler文件,不妨起名爲MyHandler.ashx,加入如下代碼,用以處理請求:
<%@ WebHandler Language="C#" Class="MyHandler2" %>
using System;
using System.Web;
public class MyHandler2 : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
string name = context.Request["name"];
if (String.IsNullOrEmpty(name))
name = "Can't get the param";
context.Response.ContentType = "text/plain";
context.Response.Write("Hello,"+name);
}
public bool IsReusable
{
get
{
return false;
}
}
}
3.用以處理請求不僅可以是上面的*.ashx文件,*.aspx,*.html文件也是可以的.