-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaxios.ts
80 lines (69 loc) · 2.08 KB
/
axios.ts
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
interface AjaxParams<T> {
AjaxType: 'Get' | 'POST';
Ajaxurl: string;
AjaxData: T;
AjaxSuccess: (res: object) => void;
}
const ajaxFn:<T>(params: AjaxParams<T>) => void = function (params) {
let { AjaxType = "post", Ajaxurl, AjaxData, AjaxSuccess } = params;
let xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.open(AjaxType, Ajaxurl, false);
xhr.send(AjaxData as any);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
let result = JSON.parse(xhr.responseText);
AjaxSuccess(result);
}
}
}
}
interface UserInfo {
username: string;
age: number;
}
ajaxFn<UserInfo>({
AjaxType: 'POST',
Ajaxurl: 'user/info',
AjaxData: {
username: 'xiaoming',
age: 18
},
AjaxSuccess(res: object) {
console.log(res)
}
})
// interface UserInfo {
// username: string;
// password: number;
// }
// class Axios<T>{
// post(url: string, data: T) : object {
// let xhr: XMLHttpRequest = new XMLHttpRequest();
// let res = {};
// xhr.open("POST", url, false);
// xhr.send(data as any);
// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// xhr.onreadystatechange = function () {
// if (xhr.readyState == 4) {
// if (xhr.status == 200 || xhr.status == 304) {
// let result = JSON.parse(xhr.responseText);
// res = result;
// }
// }
// }
// return res;
// }
// }
// let axios = new Axios<UserInfo>();
// function getUserInfo(data: UserInfo) {
// return axios.post('/user/info', data);
// }
// (async function () {
// let userInfo = await getUserInfo({
// username: 'xiaoming',
// password: 999999
// })
// console.log(userInfo) // { username:'xiaoming', sex: 1, sexName:'男', phone:'13333333333' }
// })()