——别误会,本人的博客园处女作。呵呵...
我把自己写的一个客户端Ajax辅助类与大家共享。体积小巧、简单易用、便于理解。
//Ajax辅助类。
function AjaxHelper()
{
this.OnResponse="";//服务端回传处理
this.OnError=alert;//错误信息处理
this.__staticParams__="";
this.__params__="";
this.__xmlHttp__=__createXMLHttpRequest__();
}
//添加Post提交时的参数。name和value会被自动编码;isStatic为false时(默认情况),下次调用Post方法之后参数将被清除。
AjaxHelper.prototype.AddParam=function(name,value,isStatic)
{
var param=encodeURIComponent(name)+"="+encodeURIComponent(value);
if(isStatic) this.__staticParams__+=(this.__staticParams__==""?"":"&")+param;
else this.__params__+=(this.__params__==""?"":"&")+param;
}
//Post提交。txtOrXml为"xml"时将回传一个xml文档,默认为回传文本。
AjaxHelper.prototype.Post=function(url,txtOrXml)
{
var p=this;
p.__xmlHttp__.onreadystatechange=function()
{
if(p.__xmlHttp__.readyState==4)//javascript中ActiveX对象使用this可能出现不可预期情况
{
if(p.__xmlHttp__.status==200)
{
if(p.OnResponse=="")return;
if(txtOrXml=="xml")p.OnResponse(p.__xmlHttp__.responseXML);
else p.OnResponse(p.__xmlHttp__.responseText);
}
else{ p.OnError(p.__xmlHttp__.statusText); }
}
}
p.__xmlHttp__.open("POST",url,true);
p.__xmlHttp__.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
p.__xmlHttp__.send(p.__params__+(p.__params__==""?"":"&")+p.__staticParams__);
p.__params__="";
}
function __createXMLHttpRequest__()
{
if (window.ActiveXObject)return new ActiveXObject("Microsoft.XMLHTTP");
else if(XMLHttpRequest)return new XMLHttpRequest();
else throw new Error("your browser does not support XMLHttpRequest");
}
用法举例:Default.aspx文件
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
————————————————————————————————————————
HttpHandler文件 IsUserExisted.ashx
<%@ WebHandler Language="C#" Class="IsUserExisted" %>
using System;
using System.Web;
public class IsUserExisted : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string strUserName = context.Request["UserName"].ToString();
if ("-abc-123-cwx-lxg-".LastIndexOf("-" + strUserName + "-") != -1)//如果传来的用户名为abc、123、cwx或lxg其中之一
{
context.Response.Write("user existed");
}
else context.Response.Write("ok");
}
public bool IsReusable
{
get{return false;}
}
}