我写的一个XMLHTTPREQUEST的类,作为本人在AJAX的第一帖吧
xmlhttprequest.js:
function request(onerror)
{
this.xmlhttpObj=null;
this.onError=onerror?onerror:this.defaultOnError;
this.isIE=navigator.appName.indexOf("Microsoft")!=-1?true:false;
if(this.isIE)
{
try{
this.xmlhttpObj=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
this.xmlhttpObj=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
this.onError.call(this,e);
}
}
}
else
{
this.xmlhttpObj=new XMLHttpRequest();
if(this.xmlhttpObj.overrideMimeType)
{
this.xmlhttpObj.overrideMimeType("text/xml");
}
}
}
request.prototype={
defaultOnError:function(error)
{
if(navigator.appName.indexOf("Microsoft")!=-1)
alert(error.message);
else
alert(error);
},
open:function(url,method,callback,params,headers)
{
var tempObj=this.xmlhttpObj;
var errorCall=this.onError;
var isIE=this.isIE;
method=method=="POST"?"POST":"GET";
try{
if(!tempObj)
throw (isIE?new Error(null,"请先建立连接。"):"请先建立连接。");
else
{
try{
tempObj.open(method,url,true);
if(headers)
{
for(var key in headers)
tempObj.setRequestHeader(key,headers[key]);
}
tempObj.send(params?params:null);
tempObj.onreadystatechange=function()
{
try{
if(tempObj.readyState==4&&tempObj.status==200&&callback)
{
callback.call(this,tempObj);
}
else if(tempObj.readyState==4&&tempObj.status!=200)
{
throw (isIE?new Error(null,"网页请求失败了,返回状态:"+tempObj.status):"网页请求失败了,返回状态:"+tempObj.status);
}
}catch(e){
errorCall.call(tempObj,e);
}
}
}catch(e){
throw e;
}
}
}catch(e){
this.onError.call(this,e);
}
}
}
使用范例:
<script type="text/javascript" src="xmlhttpclass.js"></script>
<script type="text/javascript">
var obj=new request();
obj.open("http://www1.5460.net","POST",function);
</script>