XMLHttpRequest封装get,post,put请求

基于XMLHttpRequest封装get,post,put请求

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
// 自定义ajax方法
class Ajax {
xmlHttpReg: any = null;
callback: Function;

constructor() {
if (window['ActiveXObject']) {// 如果是IE
this.xmlHttpReg = new window['ActiveXObject']("Microsoft.XMLHTTP");
} else if (XMLHttpRequest) {
this.xmlHttpReg = new XMLHttpRequest();
}
}

get(url, fn) {
this.callback = fn;
if (!!this.xmlHttpReg) {
this.xmlHttpReg.open("get", url, true);
this.xmlHttpReg.send(null);
// 监听返回状态
this.xmlHttpReg.onreadystatechange = _ => this.doResult();
}
}

post(url, body, fn) {
this.callback = fn;
if (!!this.xmlHttpReg) {
this.xmlHttpReg.open("POST", url, true);
// 设置参数接受类型, 如果缺少会导致服务器无法获取参数, 一定要在open和send之间调用
this.xmlHttpReg.setRequestHeader('content-type', 'application/json');
this.xmlHttpReg.send(JSON.stringify(body));
this.xmlHttpReg.onreadystatechange = _ => this.doResult();
}
}

put(url, body, fn) {
this.callback = fn;
if (!!this.xmlHttpReg) {
this.xmlHttpReg.open("PUT", url, true);
this.xmlHttpReg.setRequestHeader('content-type', 'application/json');
this.xmlHttpReg.send(JSON.stringify(body));
this.xmlHttpReg.onreadystatechange = _ => this.doResult();
}
}

doResult() {
if (this.xmlHttpReg.readyState === 4) {// 4代表执行完成
if (this.xmlHttpReg.status === 200 || this.xmlHttpReg.status === 201) {// 200代表执行成功
// 调用回调函数, 并将接口返回值传给回调函数
this.callback(JSON.parse(this.xmlHttpReg.responseText));
}
}
}
}

使用方法

put

1
2
3
4
5
6
this.ajax.put(`url`, {
phone: '',
name: ''
}, res => {
// 回调函数
});

post

1
2
3
4
5
6
7
this.ajax.post(`url`, {
phone: '',
name:''
},
res => {
// 回调函数
});

get

1
2
3
4
this.ajax.get(`http://${this.baseHref}/v1/tenants/${this.tenantId}/visitors/${this.visitorId}`, 
r => {
// 回调函数
});

注意: 如果跨域调用, 在发送post和put请求前, 会先发送一个option请求确认是否允许相应类型的请求