最近正在拜讀<<AJax in Action>>這本書,運用書中知識,結合.net,寫了這篇用.Net 處理XMLHttp發送異步請求的文章。
我們要達到的目的是點擊按鈕,獲得服務器的當前時間,ASPx的Html如下:
Html
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.ASPx.cs" Inherits="Linkedu.Web.WebWWW.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>
<script language="Javascript" src="Javascript/prototype/extras-array.JS"></script>
<script language="Javascript" src="Javascript/XMLHttp.JS"></script>
<script language="Javascript" src="Javascript/eventRouter.JS"></script>
<script language="Javascript" src="Default.JS"></script>
<script language="Javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
用Post方式獲得服務器的當前時間
<input id="btnTestPost" type="button" value="Post" />
用Get方式獲得服務器的當前時間
<input id="btnTestGet" type="button" value="Get" />
<div id="divResult"></div>
</form>
</body>
</Html>
要用Javascript 發送xmlHttp 請求必須解決的問題是跨浏覽器的支持。我們把XMLHttp的發送封裝在一個Javascript對象中,同時在這個對象中解決了跨浏覽器支持的問題。代碼如下:
XMLHttp對象
/**//*
url-loading object and a request queue built on top of it
*/
/**//* namespacing object */
var net=new Object();
net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
r> /**//*--- content loader object for cross-browser requests ---*/
net.XMLHttp=function(url, onload, params, method, contentType, onerror){
this.req=null;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
if(typeof(method) == "undefined" || method == null)
{
method = "POST";
}
this.loadXMLDoc(url, params, method, contentType);
}
net.xmlHttp.prototype.loadXMLDoc=function(url, params, method, contentType){
if (!method){
method="GET";
}
if (!contentType && method=="POST"){
contentType='application/x-www-form-urlencoded';
}
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHttp");
}
if (this.req){
try{
var loader=this;
this.req.onreadystatechange=function(){
net.XMLHttp.onReadyState.call(loader);
}
this.req.open(method,url,true);
if (contentType){
this.req.setRequestHeader('Content-Type', contentType);
}
this.req.send(params);
}catch (err){
this.onerror.call(this);
}
}
}
net.XMLHttp.onReadyState=function(){
var req=this.req;
var ready=req.readyState;
if (ready==net.READY_STATE_COMPLETE){
var httpStatus=req.status;
if (httpStatus==200 || httpStatus==0){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}
net.XMLHttp.prototype.defaultError=function(){
alert("error fetching data!"
+"\n\nreadyState:"+this.req.readyState
+"\nstatus: "+this.req.status
+"\nheaders: "+this.req.getAllResponseHeaders());
}
下面開始寫發送XMLHttp請求的代碼:
default.JS
//全局XMLHttp對象
var cobj;
/**//* Post begin*/
//綁定Post發送XMLHttp事件到btnTestPost
function loadTestPost()
{
var iobj = document.getElementById("btnTestPost");
//btnTestPost按鈕監聽的綁定
var clickRouter=new JSEvent.EventRouter(iobj,"onclick");
clickRouter.addListener(btnTestPostClick);
}
function btnTestPostClick()
{ // open參數 url, onload, params, method, contentType, onerror
cobj = new net.XMLHttp("DefaultHandler.ashx",dealResult, "<T/>", "POST");
}
/**//* Post end*/
/**//* Get begin*/
//綁定Get發送XMLHttp事件到btnTestGet
function loadTestGet()
{
var iobj = document.getElementById("btnTestGet");
//btnTestGet按鈕監聽的綁定
var clickRouter=new JSEvent.EventRouter(iobj,"onclick");
clickRouter.addListener(btnTestGetClick);
}
function btnTestGetClick()
{ // open參數 url, onload, params, method, contentType, onerror
cobj = new net.XMLHttp("DefaultHandler.ashx?T=1",dealResult, null, "GET");
}
/**//* Get end*/
function dealResult()
{
var dobj = document.getElementById("divResult");
dobj.innerHtml = cobj.req.responseXML.text;
}
window.onload = function()
{
//綁定Post發送XMLHttp事件到btnTestPost
loadTestPost();
//綁定Get發送XMLHttp事件到btnTestGet
loadTestGet();
};
最後是.Net處理XMLHttp的代碼
.Net 處理XMLHttp請求
public class DefaultHandler : IHttpHandler
{
protected XmlDocument _XMLResult;
public void ProcessRequest(HttpContext context)
{
if (context.Request["T"] != null)
{//GET XMLhttp測試
context.Response.ContentType = "text/XML";
XmlDocument xmlDoc = new XMLDocument();
xmlDoc.LoadXML(string.Format(@"<time>GET:{0}</time>", System.DateTime.Now));
XMLDoc.Save(context.Response.OutputStream);
context.Response.End();
}
else
{//POST XMLhttp測試
context.Response.ContentType = "text/XML";
XmlDocument xmlDoc = new XMLDocument();
XMLDoc.Load(context.Request.InputStream);
if (XMLDoc.DocumentElement.Name == "T")
{
xmlDoc.LoadXML(string.Format(@"<time>POST:{0}</time>", System.DateTime.Now));
XMLDoc.Save(context.Response.OutputStream);
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
http://www.cnblogs.com/Files/laiwen/XMLHttpNet.rar
http://www.cnblogs.com/laiwen/archive/2006/12/26/604050.Html