ajax类库封装

JQ中的AJAX使用以及配置项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.ajax({
url: 'xxx.json',
method: 'get', 、、//=> 在老版本的JQ中使用的是type,使用type或method效果相同
dataType: 'json', //=> |只是预设获取结果的类型,不会影响服务器结果的返回(服务器端一般给我们返回的都是json格式的字符串),如果我们预设的是json,那么类库中将把服务器返回的字符串转成JSON对象,如果我们预设的是text(默认值),我们把服务器获取的结果直接拿过来操作即可,我们预设的值还可以是xml等。
cache: false, //=> 设置是否清除缓存,只对get系列请求有作用,默认是true不清除缓存,手动设置为false,JQ类库会在请求URL的末尾追加一个随机数来清除缓存
data: null, //=> 我们通过data可以把一些信息传递给服务器,get系列请求会把data中的内容拼接在URL的末尾通过问号传参的方式传递给服务器,POST请求会把内容放在请求主题中传递给服务器;data的值可以设置为两种格式:字符串、对象,如果是字符串,设置的值是什么传递给服务器的就是什么,如果是对象,JQ会把对象变为 xxx=xxx&xxx=xxx 这样的字符串传递给服务器
async: true, //=> 设置同步或者异步,默认是异步(true)、同步(false)
success: function(res){
//=> 当ajax请求成功(readyState === 4 && status是以2|3开头的)
//=> 请求成功后JQ会把传递的回调函数执行,并且把获取的结果当做实参传递给回调函数(res就是我们从服务器端获取的结果)
},
error: function(){}, //=> 请求错误触发
complate: function(){}, //=> 不管请求是错误还是正确都会触发回调函数
})

jQuery-ajax实现

封装属于自己的AJAX类库

[支持的参数]

  • url
  • method/type
  • data
  • dataType
  • anync
  • cache
  • success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
~function(){
class ajaxClass {
//=> send ajax
init(){
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && /^[23]\d{2}$/.test(xhr.status)) {
let response = xhr.responseText;
//=> dataType 处理
try {
switch(this.dataType.toUpperCase()) {
case 'TEXT':
case 'HTML':
break;
case 'JSON':
response = JSON.parse(response);
break;
case 'XML':
response = xhr.responseXML;
break;
}
} catch (e) {
console.log(e);
}
this.success(response);
}
}

//=> data
if (this.data !== null) {
this.formatData();
if (this.isGET) {
this.url += this.querySymbol() + this.data;
this.data = null;
}
}
//=> cache
this.isGET ? this.cacheFn() : null;
xhr.open(this.method, this.url, this.async);
xhr.send(this.data);
}

//=> 把传递的对象格式转化为字符串data
formatData() {
//=> this:example
//=> 检测数据类型的四中方法 instanceof typeof constructor Object.prototype.toString.call()
if (Object.prototype.toString.call(this.data) === '[object Object]') {
let obj = this.data,
str = ``;
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
str += `${key}=${obj[key]}&`;
}
}
this.data = str.replace(/&$/g,'');
}
}

cacheFn(){
//=> this:example
!this.cache ? this.url += `${this.querySymbol()}=${Math.random()}` : null;
}

querySymbol() {
//=> this:example
return this.url.indexOf('?') > -1 ? '&' : '?'
}
}

//=> init parameters
window.ajax = function({
url=null,
method='GET',
type='GET',
data=null,
dataType='JSON',
cache=true,
async=true,
success=null
} = {}){
let _this = new ajaxClass();
['url', 'method', 'data', 'dataType', 'cache', 'async', 'success'].forEach((item) => {
if (item === 'method') {
_this.method = type === null ? method : type;
return;
}
if (item === 'success') {
_this.success = typeof success === 'function' ? success : new Function();
return;
}
_this[item] = eval(item);
});
_this.isGET = /^(GET|DELETE|HEAD)$/i.test(_this.method);
_this.init();
return _this;
}
}();