博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
基于原生XMLHttpRequest封装
阅读量:5295 次
发布时间:2019-06-14

本文共 4716 字,大约阅读时间需要 15 分钟。

 

  用了一段时间的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

你可能感兴趣的文章
PHP魔术方法之__call与__callStatic方法
查看>>
ubuntu 安装后的配置
查看>>
VSCODE更改文件时,提示:EACCES: permission denied的解决办法(mac电脑系统)
查看>>
web前端之路,js的一些好书(摘自聂微东 )
查看>>
【模板】对拍程序
查看>>
Pycharm安装Markdown插件
查看>>
【转】redo与undo
查看>>
C#更新程序设计
查看>>
解决升级系统导致的 curl: (48) An unknown option was passed in to libcurl
查看>>
Java Session 介绍;
查看>>
spoj TBATTLE 质因数分解+二分
查看>>
Django 模型层
查看>>
dedecms讲解-arc.listview.class.php分析,列表页展示
查看>>
Extjs6 经典版 combo下拉框数据的使用及动态传参
查看>>
【NodeJS】http-server.cmd
查看>>
研磨JavaScript系列(五):奇妙的对象
查看>>
面试题2
查看>>
selenium+java iframe定位
查看>>
P2P综述
查看>>
第五章 如何使用Burp Target
查看>>