1interface IOptions {
2 url: string;
3 type?: string;
4 data: any;
5 timeout?: number;
6}
7
8function formatUrl(json) {
9 let dataArr = [];
10 json.t = Math.random();
11 for (let key in json) {
12 dataArr.push(`${key}=${encodeURIComponent(json[key])}`)
13 }
14 return dataArr.join('&');
15}
16
17export function ajax(options: IOptions) {
18 return new Promise((resolve, reject) => {
19 if (!options.url) return;
20
21 options.type = options.type || 'GET';
22 options.data = options.data || {};
23 options.timeout = options.timeout || 10000;
24
25 let dataToUrlstr = formatUrl(options.data);
26 let timer;
27
28
29 let xhr;
30 if ((window as any).XMLHttpRequest) {
31 xhr = new XMLHttpRequest();
32 } else {
33 xhr = new ActiveXObject('Microsoft.XMLHTTP');
34 }
35
36 if (options.type.toUpperCase() === 'GET') {
37
38 xhr.open('get', `${options.url}?${dataToUrlstr}`, true);
39
40 xhr.send();
41 } else if (options.type.toUpperCase() === 'POST') {
42
43 xhr.open('post', options.url, true);
44 xhr.setRequestHeader('ContentType', 'application/x-www-form-urlencoded');
45
46 xhr.send(options.data);
47 }
48
49
50 xhr.onreadystatechange = () => {
51 if (xhr.readyState === 4) {
52 clearTimeout(timer);
53 if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
54 resolve(xhr.responseText);
55 } else {
56 reject(xhr.status);
57 }
58 }
59 }
60
61 if (options.timeout) {
62 timer = setTimeout(() => {
63 xhr.abort();
64 reject('超时');
65 }, options.timeout)
66 }
67
68
69
70
71
72 });
73}