前端的发展可以说非常的迅猛。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再使用,这样可以更好的兼容。