当前位置: 首页 > 工具软件 > easy-ajax > 使用案例 >

简易ajax

广宏远
2023-12-01
/**
 * 简易ajax库[脱离jquery,压缩大小1.1kb]
 * 
 * 调用方式:
 * =================================================================
 * new Ajax(url, args);
 * =================================================================
 * 
 * 参数args:
 * =================================================================
 * KEY                  VALUE
 * -----------------------------------------------------------------
 * mime                 mime type,默认为text/html
 * method               get或者post 默认为post
 * sync                 true或者false, true为异步,false同步
 * params               需要传递的参数,可以是 ka=va&kb=vb 亦可:{ka:va,kb:vb},在method为get时,忽略此参数,参数直接附在url后。
 * onComplete           回调方法:当ajax请求成功之后,调用此方法,并以request作为参数,在方法里面调用 request.responseText 则可获取请求的全部结果,默认 alert 
 * onError              回调方法,当 ajax 请求失败调用此方法,应以 error 信息作为参数,默认什么都不做
 * onLoading            回调方法,当 ajax 请求过程开始的时候调用此方法,默认什么都不做
 * =================================================================
 * 
 * 举例:
 * =================================================================
 * //get
* new Ajax(
 *      url : 'ajax.php?id=id',
 *      method : 'get',
 *      onComplete : function(raq){
 *          alert(req.responseText);                      
 *      },
 *      onError : function(error){
 *          
 *      },
 * );
 * //post
 * new Ajax(
 *      url : 'ajax.php',
 *      method : 'post',
 *      params : { 
 *                  id : id, 
 *               },
 *      onComplete : function(raq){
 *          alert(req.responseText);                      
 *      },
 *      onError : function(error){
 *          
 *      },
 * );
 * =================================================================
 * 
 * @version v1.1 2012-7-23
 * @author zxj198468@gmail.com
 */
function Ajax(url, args) {
    this.url = url || "";
    this.params = args.parameters || "";
    this.mime = args.mime || "text/html";
    this.onComplete = args.onComplete || this.defaultOnCompleteFunc;
    this.onLoading= args.onLoading || this.defaultOnLoadingFunc;
    this.onError = args.onError || this.defaultOnErrorFunc;
    this.method = args.method || "post";
   
    
    if (typeof(args.sync) == "undefined" || args.sync == null) { 
        this.sync = true;
    } else {
        this.sync = args.sync ? true : false; 
    }
    this.loadData();
}

//prototype
Ajax.prototype = {
    //状态
    READY_STATE_COMPLETE : 4,
    
    //创建XMLHttprequest对象
    getRequest : function () {
        var funcs = [
            function() {return new ActiveXObject('Msxml2.XMLHTTP')},
            function() {return new ActiveXObject('Microsoft.XMLHTTP')},
            function() {return new XMLHttpRequest()},
        ];
        var req = null;
        for (var i = 0; i < funcs.length; i++) {
            var f = funcs[i];
            try {
                req = f();
                break;
            } catch (e) {}
        }
        return req || false;
    },

    //参数处理
    parseParams : function () {
        if (typeof (this.params) == "string") {
            return this.params;
        } else {
            var s = "";
            for (var k in this.params) {
            s += k + "=" + this.params[k] + "&";
            }
            return s;
        }
    },

    //开始载入
    loadData : function () {
        this.req = this.getRequest();
        
        if (this.req) {
            this.onLoading();
            try {
                var loader = this;
                this.req.onreadystatechange = function () {
                    if (loader.req.readyState == loader.READY_STATE_COMPLETE) {
                        loader.onComplete.call(loader, loader.req);
                    }
                };
                this.req.open(this.method, this.url, this.sync);

                if (this.method == "post") {
                    this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                }

                if (this.req.overrideMimeType) {
                    this.req.overrideMimeType(this.mime);
                }
                this.req.send(this.method == "post" ? this.parseParams(this.params) : null);
            } catch (e) {
                this.onError.call(this, e);
            }
        }
    },

    //默认完成处理函数
    defaultOnCompleteFunc : function () {
        alert(this.req.responseText);
    },

    //默认前置函数
    defaultOnLoadingFunc : function () {
    },

    //默认错误处理函数
    defaultOnErrorFunc : function (error) {
    }
}


//举例

//Ajax的GET请求举例
function test_get(){
	var url = 'ajax.php?act=ok';
	new Ajax(url, {
	    method  : 'get',
		onComplete : function(req){
		    alert(req.responseText);
		},
		onError : function(error){
		    //alert(error);
		},
		onLoading : function(){
			//alert('GET即将开始……');
		}
	});
}

//Ajax的POST请求举例
function test_post(){
	var url = 'ajax.php';
	new Ajax(url, {
	     method : 'post',
	     parameters : { 
	                     act : 'ok', 
	                  },
	     onComplete : function(req){
	         alert(req.responseText);                      
	     },
	     onError : function(error){
	    	//alert(error);
	     },
	     onLoading : function(){
	         //alert('POST即将开始……');
	     }
	});
}


 类似资料: