ajax的封装

//本来想写个ajax的封装的,但在情封的项目中无意看到这段源码,和我刚开始的构思差不多,果断copy过来参考,做了一点修改。
var Ajax = {
    createXHR:function () {
        if (typeof XMLHttpRequest !== 'undefined') {
            return new XMLHttpRequest();
        } else if (typeof ActiveXObject !== 'undefined') {
            if (typeof arguments.callee.activeXString !== 'string') {
                var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp'];
                for (var i = 0, len = versions.length; i < len; i++) {
                    try {
                        var xhr = new ActiveXObject(versions[i]);
                        arguments.callee.activeXString = versions[i];
                        return xhr;
                    } catch (ex) {

                    }
                }
            }
            return new ActiveXObject(arguments.callee.activeXString);
        } else {
            throw new Error('No xhr object available');
        }
    },
    responseType:function (request) {
        var _responseType = request.getResponseHeader('Content-Type');
        switch (_responseType) {
            case 'text/xml':
                return request.responseXML;
            case 'text/json':
            case 'text/javascript':
            case 'application/javascript':
            case 'application/x-javascript':
                return eval('(' + request.responseText + ')');
            default:
                return request.responseText;
        }
    },
    encodeFormData:function (data) {
        var _pairs = [];
        var _regexp = /%20/g;
        for (var name in data) {
            var _value = data[name].toString();
            var _pair = encodeURIComponent(name).replace(_regexp, '+') + '=' + encodeURIComponent(_value).replace(_regexp, '+');
            _pairs.push(_pair);
        }
        return _pair.join('&');
    },
    /**
     * 执行ajax请求
     * @param {String} method 'GET' || 'POST'
     * @param {String} url 
     * @param {Boolean} asyn 是否异步加载
     * @param {Object} callback {success,failure} 回调对象,存放函数
     * @param value
     */
    ajaxRequest:function (method, url, asyn, callback, value) {
        var _xhr = this.createXHR();
        _xhr.onreadystatechange = function () {
            if (_xhr.readyState === 4) {
                if (_xhr.status >= 200 && _xhr.status < 300 || _xhr.status === 300) {
                    callback.success(this.responseType(_xhr));
                } else {
                    if (callback.failure) {
                        callback.failure(_xhr.status, _xhr.statusText);
                    }
                }
            }
        };

        _xhr.open(method, url, asyn);

        if (method === 'GET') {
            _xhr.send(null);
        } else if (method === 'POST') {
            _xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            _xhr.send(this.encodeFormData(value));
        }
    }
};

  

posted @ 2012-12-16 13:18  LukeLin  阅读(189)  评论(0编辑  收藏  举报