Recently, I am reading the book <<Ajax in Action>>. I used the knowledge in the book and combined with .net to write this article about using .net to process xmlHttp to send asynchronous requests.
What we want to achieve is to click the button to get the current time of the server. The html of aspx is as follows:
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>Test</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">
Get the current time of the server using Post method
<input id="btnTestPost" type="button" value="Post" />
Get the current time of the server using Get method
<input id="btnTestGet" type="button" value="Get" />
<div id="divResult"></div>
</form>
</body>
</html>
To use javascript to send xmlHttp requests, the problem that must be solved is cross-browser support. We encapsulate the sending of xmlHttp in a javascript object, and at the same time solve the problem of cross-browser support in this object. The code is as follows:
xmlHttp object
/**//*
url-loading object and a request queue built on top of it
*/
/**//* namepacing 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;
/**//*--- 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!"
+"nnreadyState:"+this.req.readyState
+"nstatus: "+this.req.status
+"nheaders: "+this.req.getAllResponseHeaders());
}
Let's start writing the code to send xmlHttp request:
default.js
//Global xmlHttp object
var cobj;
/**//* Post begin*/
//Bind Post to send xmlHttp event to btnTestPost
function loadTestPost()
{
var iobj = document.getElementById("btnTestPost");
//Binding for btnTestPost button listening
var clickRouter=new jsEvent.EventRouter(iobj,"onclick");
clickRouter.addListener(btnTestPostClick);
}
function btnTestPostClick()
{ // open parameters url, onload, params, method, contentType, onerror
cobj = new net.xmlHttp("DefaultHandler.ashx",dealResult, "<T/>", "POST");
}
/**//* Post end*/
/**//* Get begin*/
//Bind Get to send xmlHttp event to btnTestGet
function loadTestGet()
{
var iobj = document.getElementById("btnTestGet");
//btnTestGet button listening binding
var clickRouter=new jsEvent.EventRouter(iobj,"onclick");
clickRouter.addListener(btnTestGetClick);
}
function btnTestGetClick()
{ // open parameters 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()
{
//Bind Post to send xmlHttp event to btnTestPost
loadTestPost();
//Bind Get to send xmlHttp event to btnTestGet
loadTestGet();
};
The last is the code for .net processing xmlHttp
.net handles xmlHttp requests
public class DefaultHandler : IHttpHandler
{
protected XmlDocument _xmlResult;
public void ProcessRequest(HttpContext context)
{
if (context.Request["T"] != null)
{//GET xmlhttp test
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 test
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/laiwen/archive/2006/12/26/604050.html