基于原生XMLHttpRequest封装

  用了一段时间的Ajax,感觉有很多的不足之处,于是就封装原生了 XMLHttpRequest 。

  废话不多说,直接上代码。

  

var http = function () {
    'use strict';   //strict mode

    var get = function (options) {
        if (!options.url) throw "url is not defined";
        options.type = "get";
        request(options);
    };

    var post = function (options) {
        if (!options.url) throw "url is not defined";
        options.type = "post";
        request(options);
    };

    var fileUpload = function (options) {
        if (!options.url) throw "url is not defined";

        var _form = new FormData();
        _form.append("file", options.file);
        if (options.data) {
            for (var i in options.data) {
                _form.append(i, options.data[i]);
            }
        }
        var _url = options.url;
        var _xhr = new XMLHttpRequest();
        var _async = true;
        if (typeof options.async == "boolean") _async = options.async;
        _xhr.open("post", _url, _async);
        if (options.header) {
            var _header = options.header;
            for (var i in _header) {
                _xhr.setRequestHeader(i, _header[i]);
            }
        }
        _xhr.onload = function (result) {
            if (result && result.target.responseText) {
                if (result.target.status == 200) {
                    try {
                        var _data = JSON.parse(result.target.responseText);
                        if (typeof options.success == "function") options.success(_data);
                    } catch (e) {
                        if (typeof options.success == "function") options.success(result.target.responseText);
                    }
                } else {
                    alert("Error : " + result.target.status + "(" + result.target.statusText + ")");
                    if (typeof options.error == "function") options.error(result.target.responseText);
                }
            }
        };
        _xhr.send(_form);
        _xhr.onloadend = function () {
            _xhr = null;
        }
    };

    return {
        get: get,
        post: post,
        fileUpload: fileUpload
    }

    function request(options) {
        var _xhr = new XMLHttpRequest();
        var _sendstr = formRequestData(options.data);
        if (options.setTimeout) {
            _xhr.timeout = options.setTimeout;
        }
        else _xhr.timeout = 18e4;      //Default mode for time out is 3 minute.

        var _async = true;
        if (typeof options.async == "boolean") {
            _async = options.async;
            if (_async == false) _xhr.timeout = 0;    //Synchronous request for time out must be set 0. Details view https://www.w3.org/TR/XMLHttpRequest/
        }

        if (options.type == "get") {
            if (_sendstr) options.url = options.url + "?" + _sendstr;
        }

        _xhr.open(options.type, options.url, _async);
        _xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); 
        if (options.header) {
            var _header = options.header;
            for (var i in _header) {
                _xhr.setRequestHeader(i, _header[i]);
            }
        }

        if (typeof options.beforeSend == "function") options.beforeSend(_xhr);

        _xhr.onload = function (result) {
            if (result && result.target.responseText) {
                if (result.target.status == 200) {
                    try {
                        var _data = JSON.parse(result.target.responseText);
                        if (typeof options.success == "function") options.success(_data);
                    } catch (e) {
                        if (typeof options.success == "function") options.success(result.target.responseText);
                    }
                } else {
                    alert("Error : " + result.target.status + "(" + result.target.statusText + ")");
                    if (typeof options.error == "function") options.error(result.target.responseText);
                }
            }
        };

        _xhr.ontimeout = function (e) {
            if (typeof options.timeout == "function") options.timeout(e);
            _xhr.abort();
            alert("Request timeout.");
        }

        _xhr.onabort = function (e) {
            if (typeof options.abort == "function") options.abort(e);
        }

        _xhr.send(_sendstr);

        _xhr.loadend = function () {
            _xhr = null;                //Close the XMLHttpRequest.
        }
    }

    function formRequestData(data) {
        var _sendstr = null;
        if (data) {
            _sendstr = '';
            for (var i in data) {
                _sendstr += (_sendstr ? '&' : '') + i + '=' + encodeURIComponent(data[i]);
            }
        }
        return _sendstr
    }
}();

  代码写的不好......大神勿喷!

原文地址:https://www.cnblogs.com/jiangyangtao/p/8426335.html