一个简单的Ajax类
作者: 青锋幽灵 日期: 2008-09-08 11:44
JavaScript代码
- /**
- Powered By CMSDream Copyright © 2007-2008 All rights reserved.
- 14:21 2008-5-10
- **/
- function CMSDreamAjaxLib(){
- /**//**
- 成员变量
- */
- this.XMLHttpReq = null; //XML对象
- this.method = "post"; //执行的方法(post/get)
- this.url = ""; //异步调用的页面地址
- this.responseText = ""; //异步返回的响应字符串
- this.responseXML = ""; //异步返回的响应XML
- this.failed = false; //创建对象错误标志
- /**//**
- 事件区
- */
- this.onLoading = function() {}; //正在发送请求
- this.onLoaded = function() {}; //已经接收到全部响应内容
- this.onInteractive = function() {}; //正在解析响应内容
- this.onCompletion = function() {}; //响应内容解析完成
- this.onError = function() {}; //异步错误处理事件
- this.onFail = function() {}; //创建对象失败处理世界
- /**//**
- 重置所有事件函数
- */
- this.resetFunctions = function() {
- this.onLoading = function() {};
- this.onLoaded = function() {};
- this.onInteractive = function() {};
- this.onCompletion = function() {};
- this.onError = function() {};
- this.onFail = function() {};
- };
- /**//**
- 初始化函数(构造时自动初始化)
- */
- this.init = function(){
- if(window.XMLHttpRequest){
- this.XMLHttpReq = new XMLHttpRequest();
- }else if (window.ActiveXObject){
- try{this.XMLHttpReq = new ActiveXObject("Msxml4.XMLHTTP");}
- catch(e){
- try{this.XMLHttpReq = new ActiveXObject("Msxml3.XMLHTTP");}
- catch(e){
- try{this.XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");}
- catch(e){
- try{this.XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");}
- catch(oc){this.failed=true;}
- }
- }
- }
- }
- };
- /**//**
- 发送请求函数
- @param data 发送的数据
- @example send("id=1");
- */
- this.send=function(data){
- var self=this;
- if(this.method=="post") {
- this.XMLHttpReq.open(self.method,self.url,true);
- }else{
- this.XMLHttpReq.open(self.method,self.url+"?"+encodeURI(data),true);
- }
- //添加消息响应头
- this.XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
- //异步回调函数
- this.XMLHttpReq.onreadystatechange = function(){
- //对象未创建
- if (self.failed) {
- self.onFail();
- return;
- }
- //消息响应标志
- switch (self.XMLHttpReq.readyState) {
- case 1:{
- self.onLoading();
- break;
- }
- case 2:{
- self.onLoaded();
- break;
- }
- case 3:{
- self.onInteractive();
- break;
- }
- case 4:{
- self.responseText = self.XMLHttpReq.responseText;
- self.responseXML = self.XMLHttpReq.responseXML;
- self.onCompletion();
- break;
- }
- }
- };
- if(this.method=="post"){
- this.XMLHttpReq.send(data); //发送请求
- }else{
- this.XMLHttpReq.send(); //发送请求
- }
- };
- this.abort=function(){
- this.XMLHttpReq.abort();
- }
- this.close=function(){
- this.XMLHttpReq=null;
- }
- this.init();
- }
发表评论
订阅
标签:
