自己编写的ajax类_javascript

前些天,自己特别忠于对javascript的学习,看到网上出色的javascript AJAX应用,于是变萌发了编写一个属于自己的Ajax类的想法。

代码还有很多不足,希望各位大侠们帮忙之处,小弟在这不慎感激!

此类还在不断优化中。。。呵呵

说明:

  1. 提供Ajax.get()发送请求
  2. 提供Ajax.post()发送请求
  3. 内部绑定定时函数来执行循环发送请求
  4. 合理处理空闲请求

/*
 * Ajax-lib.js
 * {by}d.n.sky
 * {website}desetang.com
 * {description}Ajax类
 */
var Ajax = function(){};
/* 创建请求基础类 */
Ajax.prototype = {
    /* 重新发送请求时间(请求未完成) */
    retryDelay: 5,
    /* 是否对未完成的队列进行定时处理 */
    isDisp: false,
    /* 缓存对象 */
    cacheXMLHttp: [],
    /* 二维数组储存(记录请求中text/html/xml的最后修改时间) */
    lastModified: [],
    /* 返回xmlhttp对象 */
    getFreeXMLHttp: function(){
        /* 从对象池中获取空闲请求 */
        for(var i = 0, len = this.cacheXMLHttp.length; i < len; i++){
            var cXMLHttp = this.cacheXMLHttp[i];
            /* 如果XMLHttpRequesst的 readyState为0或4,确定当前对象闲置 */
            if(cXMLHttp.readyState === 0 || cXMLHttp.readyState === 4){
                return cXMLHttp;
                }
            }
            /* 没有空闲创建对象 */
            this.cacheXMLHttp[this.cacheXMLHttp.length] = this.createXmlHttp();
            return this.cacheXMLHttp[this.cacheXMLHttp.length - 1];
        },
    /* 创建xmlhttp */
    createXmlHttp: function(){
        var methods = [
        function(){ return new XMLHttpRequest();},
        function(){ return new ActiveXObject('Msxml2.XMLHTTP');},
        function(){ return new ActiveXObject('Microsoft.XMLHTTP');}
        ];
        for(var i=0;i<methods.length;i++){
            try{
                methods[i]();
                }catch(e){continue}
                return methods[i]();
            }
            this.error('Could not create xmlhttp.');
        },
       
    /* 处理URL(增加随机参数,防止IE缓存服务器响应) */
    makeURL: function(url){
        var _s;
        (url.indexOf('?') > 0)? _s = '&': _s = '?';
        url += _s + 'rand-num-url=' + Math.random();
        return url;
        },
       
    /* 设置请求头 */
    setRequestHeader:{
        html: "text/html",
        xml: "application/xml, text/xml",
        json: "application/json, text/javascript",
        javascript: "text/javascript, application/javascript",
        text: "text/plain",
        },
   
    /* 获取是否更新文件(针对html/xml/js) */
    isNotLastModify: function (obj, url){
        var lastModified = obj.getResponseHeader("Last-Modified");
        var    etag = obj.getResponseHeader("Etag");
        this.lastModified[url] = [lastModified,etag];
        return this.lastModified[url];
        },
   
    /* 工具类 */
    parseJSON: function (data){
            if(!data || typeof data != 'string'){
                return null;
                }
            return eval('(' + data + ')');
    },
   
    /* 执行代码(JavaScript) */
    conEval: function(data){
        if(data){
            var head = document.getElementsByTagName('head')[0].lastChild || document.documentElement.firstChild;
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.appendChild(document.createTextNode(data));
            this.insertAfter(script, head);
            }
            return data;
        },
       
    /* insertAfter(newElement, element) */
    insertAfter: function(newEle, ele){
        var _p = ele.parentNode;
        (_p.lastChild == ele)? _p.appendChild(newEle) : _p.insertBefore(newEle, ele.nextSibling);
        },
   
    /* 判断类型输出处理结果 */
    echoType: function(obj, type){
        /* 获取相应content-type */
        var _ct = obj.getResponseHeader("Content-Type") || '';
        var xml = (type === 'xml' || _ct.indexOf('xml') >= 0);
        var json = (type === 'json' || _ct.indexOf('json') >= 0);
        var script = (type === 'javascript' || _ct.indexOf('javascript') >= 0);
        var data = xml ? obj.responseXML : obj.responseText;
       
        /* xml 结构错误 */
        if(xml){
            var er = data.documentElement.nodeName;
            if( er == 'parsererror') this.error('XML parsererror.');
            };
       
        /* javascript xml */
        if(typeof data === 'string'){
            /* 处理json */
            if(json) data = this.parseJSON(data);
            /* 处理script */
            if(script) data = this.conEval(data);
            }
       
        return data;
        },
       
    /* Error */
    error: function(msg){
        throw msg;
        },
    /* 定时器 */
    setTimeOut: function(timer, fn){
        setTimeout(fn, timer * 1000);
        },
   
    /* 处理服务器响应 */
    request: function(G, callback){
       
        /* 处理数据 */
        //var method, url, data, type, timer, async;
        method = G.method.toUpperCase();
        url = G.url;
        data = (method == 'POST')? this.hybridPar(G.data) : G.data;
        type = G.type.toLowerCase();
        timer = G.timer;
        async = G.async;
       
        /* 默认异步处理数据 */
        if(async == null) async = true;
        /* 创建xmlhttp对象 */
        var xmlhttp = this.getFreeXMLHttp();
        var firstUrl = url; /* 储存原始url */
        if(method == 'GET') url = this.makeURL(url);
        var that = this;/* 储存this */
        /* 设置初始状态 */
        var start = true;
       
        /* _fn 结果综合处理函数 */
        var _fn = function(){
            if(xmlhttp.readyState !== 4) return;
            if(xmlhttp.readyState === 4){
                start = false;
                if(xmlhttp.status === 200 || (xmlhttp.status === 304 && that.lastModified[firstUrl])){
                   
                    that.isNotLastModify(xmlhttp, firstUrl);
                    if(typeof callback.success != 'undefined'){
                        if(xmlhttp.status === 200) callback.success(that.echoType(xmlhttp, type));
                        if(timer != null){
                            var _t = function(){
                                G.url = firstUrl;
                                that.request(G, callback);
                            };
                            that.setTimeOut(timer, _t)
                       }
                    }
               }else{
                   if(typeof callback.failure != 'undefined'){
                       callback.failure(xmlhttp.status);
                       /* 重新发送错误请求 */
                       if(that.isDisp){
                           var _t = function(){
                               G.url = firstUrl;
                               G.timer = null;
                               that.request(G, callback);
                            }
                            that.setTimeOut(timer, _t);
                           }
                       }
                   }
               }
            }

            /* async == true */
            if(async == true) xmlhttp.onreadystatechange = _fn;

            /* 打开与服务器连接 */
            xmlhttp.open(method, url, async);
           
            xmlhttp.setRequestHeader("Content-type",this.setRequestHeader[type.toLowerCase()]);
            /* 设置请求头,当请求内容在指定的日期之后又经过修改才返回,否则返回 304(针对url被清缓存处理)*/
            if( this.lastModified[firstUrl] && (type == 'xml' || type == 'html' || type == 'text' || type == 'javascript')){
                xmlhttp.setRequestHeader("If-Modified-Since", this.lastModified[firstUrl][0]);
                xmlhttp.setRequestHeader("If-None-Match", this.lastModified[firstUrl][1]);
            }
            xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            /* GET */
            if(method === 'GET') data = null;
           
            /* post 方式设置请求头 */
            if(method == 'POST'){
                /* post application/x-www-form-urlencoded*/
                xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                }
            this.isNotLastModify(xmlhttp, firstUrl);
            xmlhttp.send(data);
            /* async==false */
            if(async == false) _fn();
        },
   
    /* 文件格式判断 */
    fileLay: function (layout, ty){
        var static = ['.html','.dhtml','.txt','.xml','.txt','.js'];
        var trends = ['.php','.asp','.aspx','.jsp'];
        var _, result = false;
        if(ty == null) _ = static.concat(trends);
        if(ty == 0) _ = static;
        if(ty == 1) _ = trends;
        /* 获取文件格式后缀 */
        if(layout.indexOf('?') >= 0) layout = layout.substr(0, layout.indexOf('?'));
        if(layout.lastIndexOf('/') >= 0) layout = layout.substr(layout.lastIndexOf('/') + 1, layout.length);
        layout = layout.toLowerCase();
        for(var i = 0, len = _.length; i < len; i++){
            if(layout.indexOf(_[i]) >= 0) result = true;
            }
            return result;
        },
       
    /* (post方式)增加参数设置{'s':'1','t':'0'}/'s=1&t=0' */
    hybridPar: function(data){
        /* {'s':6,'t':'ui'}->s=6&t=ui */
        if(typeof data == 'object'){
            var _s = '';
            for(var key in data){
                _s = _s + key + '=' + escape(data[key]) + '&'
                }
            if(_s !== undefined){
                if(_s.indexOf('&') >= 0) _s = _s.substr(0, _s.length - 1);
            }else{
                _s = null
            };
            return _s;
        }
        /* t=1&d=4&g=6 */
        if(typeof data == 'string'){
            return data;
            }
        },
   
    /* Ajax.get */
    get: function(calle, callback){
        calle.method = 'get';
        this.request(calle, callback);
        },
       
    /* Ajax.get */
    post: function(calle, callback){
        /* 静态文件不允许响应POST请求 */
        calle.method = 'post';
        if(this.fileLay(calle.url, 0) == true) calle.method = 'get';
        this.request(calle, callback);
        }
};


你可能感兴趣的:(JavaScript,js学习,post请求,ajax应用,AJAX类)