XMLHttpRequest纯JavaScript的AJAX

5 篇文章 0 订阅

前端的发展可以说非常的迅猛。Bootstrap官方在不久之前发布声明,在5.0版本将要摆脱对jQuery的依赖。早在上次GitHub更新的时候,就已经完全对jQuery说拜拜了。

虽然在后jQuery时代,也有很多第三方包提供Ajax的能力。但是虚的不如实的,掌握XMLHttpRequest是迟早的事情,用纯JavaScrips进行Ajax可以更好处理。

废话不多说,下面附上常用的GET和POST方法的dome。

/**
 * create by dmt_csr
 * 2019/02/27
 */

//封装常用POST方法的 Content-Type
const CONTENT_TYPE = {
    X_WWW_FORM_URLENCODED: 'application/x-www-form-urlencoded;charset=utf-8',
    MULTIPART: 'multipart/form-data;charset=utf-8',
    JSON: 'application/json;charset=utf-8',
    XML: 'text/xml;charset=utf-8',
};

//方式 封装常用 GET POST
const AJAX_METHODS = {
    GET: 'GET',
    POST: 'POST'
};

class httpRequestNode {
    constructor() {
        this._httpRequest = null;
        this.new();
    }

    new() {
        let _this = this;
        if (window.XMLHttpRequest) {
            // 适用于现代浏览器
            _this._httpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            // 对 IE5 , IE6 进行兼容
            _this._httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //创建失败提示
        if (!_this._httpRequest) {
            console.error('Giving up :( Cannot create an XMLHTTP instance');
        }
    }

    get() {
        return this._httpRequest;
    }
}

/**
 * AjaxHttpRequest类也可以继承 httpRequestNode类
 * 但是在这里选择作为成员,而不是继承。
 * 主要考虑的是降低耦合性
 */
class AjaxHttpRequest {
    /**
     * @param methods 方法
     * @param url 路由
     * @param data 提交的数据
     * @param callback 回调函数
     * @param contentType
     */
    constructor(methods, url, callback = null, data = null, contentType = null) {
        //创建 XMLHttpRequest,并获取
        this._httpRequest = new httpRequestNode().get();
        this._methods = methods;
        this._url = encodeURI(url);
        this._data = data;
        this._contentType = contentType;
        this._callback = callback;
    }

    start() {
        let _this = this;
        const SUCCESS_STATUS = 200;
        _this._httpRequest.onreadystatechange = function () {
            //状态值 4 完成后进入
            if (_this._httpRequest.readyState === XMLHttpRequest.DONE) {
                //200 ok
                //404 not found
                if (_this._httpRequest.status === SUCCESS_STATUS) {
                    if (_this._callback) _this._callback(_this._httpRequest.responseText);
                } else {
                    console.error('There was a problem with the request.');
                }
            }
        };
        _this._httpRequest.open(_this._methods, _this._url);
        //POST 方法,并且Content-Type 不为空时 进行设置
        if (_this._methods === AJAX_METHODS.POST && _this._contentType !== null) {
            _this._httpRequest.setRequestHeader("Content-Type", _this._contentType);
        }
        _this._httpRequest.send(_this._data);
    }
}

以上的代码最好还是用Babel转成ES5再使用,这样可以更好的兼容。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值