-
Notifications
You must be signed in to change notification settings - Fork 2
/
ajax.ts
222 lines (197 loc) · 5.58 KB
/
ajax.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/**
* 提供基于 XMLHttpRequest(或 XDomainRequest) 的 AJAX 请求接口。
* @packageDocumentation
*/
import { assignProps, isEmpty } from '@just4/util/object';
import { isObject } from '@just4/util/type';
import { stringify, concat } from '@just4/querystring/index';
import { isOldIE, isCrossDomain } from './internal/util';
import {
createAJAXRecord,
deleteAJAXRecord,
cancelRequest
} from './internal/ajax-record';
import {
BodyType,
RequestMethod,
RequestType,
IAJAXOptions,
IAJAXResponse
} from './interfaces';
import { AJAXError } from './ajax-error';
// IE 9 不支持 XMLHttpRequest 的跨域请求,符合条件时,使用 XDomainRequest
function createXhr(
isCross: boolean,
method: string,
requestType: string,
headers: object,
withCredentials?: boolean
): XMLHttpRequest {
const useXDomainRequest = isCross &&
isOldIE() &&
(<any>window).XDomainRequest &&
(method === 'get' || method === 'post') &&
!requestType &&
!withCredentials &&
isEmpty(headers);
return useXDomainRequest
? new (<any>window).XDomainRequest()
: new window.XMLHttpRequest();
}
// 拼接出最终请求的 URL
function handleURL(
url: string,
params?: object | string,
preventCaching?: boolean
): string {
url = concat(url, params, { ignoreEmpty: false });
// 在 URL 上增加时间戳参数以防止缓存
if (preventCaching) { url = concat(url, { _: Date.now() }); }
return url;
}
// 处理请求主体
function handleRequestBody(
method: RequestMethod,
headers: any,
data?: string | object,
requestType?: string
): BodyType | undefined {
if (data == null || method === 'get') { return; }
let body: BodyType;
let contentType: string | undefined;
if (requestType === 'json') {
body = typeof data === 'string' ? data : JSON.stringify(data);
contentType = 'application/json; charset=utf-8';
} else {
body = isObject(data)
? stringify(data, { ignoreEmpty: false })
: <BodyType>data;
if (typeof body === 'string') {
contentType = 'application/x-www-form-urlencoded; charset=utf-8';
}
}
headers['Content-Type'] = headers['Content-Type'] || contentType;
return body;
}
// 发送请求前,设置 XMLHttpRequest 对象的属性和请求头
function setXhrPropsAndHeaders(
xhr: XMLHttpRequest,
options: Readonly<IAJAXOptions>,
isCross: boolean,
headers: any
) {
// 在IE中,超时属性可能只能在调用 open() 方法之后且在调用 send() 方法之前设置
if (options.timeout) { xhr.timeout = options.timeout; }
// 跨域才需要设置 withCredentials
if (isCross && options.withCredentials != null) {
xhr.withCredentials = !!options.withCredentials;
}
// 同域才设置 X-Request-With,避免跨域情况下没有允许这个自定义头
if (!isCross && headers['X-Request-With'] == null) {
headers['X-Request-With'] = 'XMLHttpRequest';
}
// 自定义请求头
Object.keys(headers).forEach(function(key) {
if (headers[key] != null) {
xhr.setRequestHeader(key, String(headers[key]));
}
});
}
/**
* 发送 AJAX 请求。
* @example
* ```typescript
* import { send } from '@just4/ajax/ajax';
* const { data } = await send('/api/ajax/json', {
* method: 'get',
* params: { num: 100 }
* });
* const { data } = await send('/api/ajax/json', {
* method: 'post',
* data: { num: 100 }
* });
* ```
* @param url 请求 URL。
* @param options 请求选项。
* @returns 发送请求的 promise 实例。
*/
export function send(
url: string, options?: Readonly<IAJAXOptions>
): Promise<IAJAXResponse> {
let xhrId = 0;
return new Promise<IAJAXResponse>(function(resolve, reject): void {
const opts = assignProps<IAJAXOptions>({}, options);
opts.method = opts.method || 'get';
opts.requestType = opts.requestType || '';
opts.responseType = opts.responseType || 'json';
opts.timeout = opts.timeout || 0;
opts.method = <RequestMethod>opts.method.toLowerCase();
opts.requestType = <RequestType>opts.requestType.toLowerCase();
opts.headers = opts.headers || {};
Object.freeze(opts);
url = handleURL(url, opts.params, opts.preventCaching);
const isCross = isCrossDomain(url);
const xhr = createXhr(
isCross,
opts.method,
opts.requestType,
opts.headers,
opts.withCredentials
);
xhrId = createAJAXRecord(
xhr,
opts,
function(response: IAJAXResponse) {
deleteAJAXRecord(xhrId);
resolve(response);
},
function(error: AJAXError) {
deleteAJAXRecord(xhrId);
reject(error);
}
);
if (opts.responseType === 'blob' || opts.responseType === 'arraybuffer') {
xhr.responseType = opts.responseType;
}
xhr.open(
opts.method,
url,
true,
opts.username,
opts.password
);
const body = handleRequestBody(
opts.method,
opts.headers,
opts.data,
opts.requestType
);
setXhrPropsAndHeaders(xhr, opts, isCross, opts.headers);
if (typeof opts.beforeSend === 'function') {
opts.beforeSend.call(window, xhr);
}
xhr.send(body || '');
if (typeof opts.receiveCancelId === 'function') {
opts.receiveCancelId(xhrId);
}
});
}
/**
* 中断 AJAX 请求。
* @example
* ```typescript
* import { send, cancel } from '@just4/ajax/ajax';
* let ajaxId = 0;
* send('/api/ajax/timeout', {
* receiveCancelId: function(id) { ajaxId = id; }
* });
* // 2s 后中断请求
* setTimeout(function() {
* cancel(ajaxId);
* }, 2000);
* ```
* @param id AJAX 请求编号。
*/
export function cancel(id: number): void {
cancelRequest(id);
}