@codady/utils 0.0.38 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/utils.cjs.js +472 -23
- package/dist/utils.cjs.min.js +2 -2
- package/dist/utils.esm.js +472 -23
- package/dist/utils.esm.min.js +2 -2
- package/dist/utils.umd.js +472 -23
- package/dist/utils.umd.min.js +2 -2
- package/dist.zip +0 -0
- package/examples/ajax-get.html +59 -0
- package/examples/ajax-hook.html +55 -0
- package/examples/ajax-method.html +36 -0
- package/examples/ajax-post.html +37 -0
- package/examples/buildUrl.html +99 -0
- package/examples/getUrlHash.html +71 -0
- package/modules.js +13 -1
- package/modules.ts +13 -1
- package/package.json +1 -1
- package/src/ajax.js +363 -0
- package/src/ajax.ts +450 -0
- package/src/buildUrl.js +64 -0
- package/src/buildUrl.ts +86 -0
- package/src/capitalize - /345/211/257/346/234/254.js" +19 -0
- package/src/capitalize.js +19 -0
- package/src/capitalize.ts +20 -0
- package/src/cleanQueryString.js +19 -0
- package/src/cleanQueryString.ts +20 -0
- package/src/getBodyHTML.js +53 -0
- package/src/getBodyHTML.ts +61 -0
- package/src/getEl.js +1 -1
- package/src/getEl.ts +6 -5
- package/src/getEls.js +1 -1
- package/src/getEls.ts +5 -5
- package/src/getUrlHash.js +37 -0
- package/src/getUrlHash.ts +39 -0
- package/src/isEmpty.js +24 -23
- package/src/isEmpty.ts +26 -23
- package/src/sliceStrEnd.js +63 -0
- package/src/sliceStrEnd.ts +60 -0
package/src/ajax.js
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/20 16:38:21
|
|
3
|
+
* Sends an asynchronous HTTP request (AJAX).
|
|
4
|
+
* @function ajax
|
|
5
|
+
* @param {AjaxOptions} options - Configuration for the request.
|
|
6
|
+
* @returns {Promise<AjaxResponse>} Returns a promise that resolves with the response context.
|
|
7
|
+
* @example
|
|
8
|
+
* ajax({ url: '/api/data', method: 'GET' }).then(res => console.log(res.content));
|
|
9
|
+
*/
|
|
10
|
+
'use strict';
|
|
11
|
+
import isEmpty from './isEmpty';
|
|
12
|
+
import getDataType from './getDataType';
|
|
13
|
+
import getBodyHTML from './getBodyHTML';
|
|
14
|
+
import getUrlHash from './getUrlHash';
|
|
15
|
+
import capitalize from './capitalize';
|
|
16
|
+
import buildUrl from './buildUrl';
|
|
17
|
+
import cleanQueryString from './cleanQueryString';
|
|
18
|
+
const ajax = (options) => {
|
|
19
|
+
// Validation
|
|
20
|
+
if (isEmpty(options)) {
|
|
21
|
+
return Promise.reject(new Error('Options are required'));
|
|
22
|
+
}
|
|
23
|
+
if (!options.url || typeof options.url !== 'string') {
|
|
24
|
+
return Promise.reject(new Error('URL is required and must be a string'));
|
|
25
|
+
}
|
|
26
|
+
// Default configuration
|
|
27
|
+
const config = {
|
|
28
|
+
url: '',
|
|
29
|
+
method: 'POST',
|
|
30
|
+
async: true,
|
|
31
|
+
selector: '',
|
|
32
|
+
data: null,
|
|
33
|
+
timeout: 3600000,
|
|
34
|
+
headers: {},
|
|
35
|
+
responseType: '',
|
|
36
|
+
catchError: false,
|
|
37
|
+
signal: null,
|
|
38
|
+
xhrFields: {},
|
|
39
|
+
cacheBustKey: '_t',
|
|
40
|
+
//
|
|
41
|
+
onAbort: null,
|
|
42
|
+
onTimeout: null,
|
|
43
|
+
//
|
|
44
|
+
onBeforeSend: null,
|
|
45
|
+
//
|
|
46
|
+
onCreated: null,
|
|
47
|
+
onOpened: null,
|
|
48
|
+
onHeadersReceived: null,
|
|
49
|
+
onLoading: null,
|
|
50
|
+
//
|
|
51
|
+
onSuccess: null,
|
|
52
|
+
onFailure: null,
|
|
53
|
+
onInformation: null,
|
|
54
|
+
onRedirection: null,
|
|
55
|
+
onClientError: null,
|
|
56
|
+
onServerError: null,
|
|
57
|
+
onUnknownError: null,
|
|
58
|
+
onError: null,
|
|
59
|
+
onFinish: null,
|
|
60
|
+
//
|
|
61
|
+
onDownload: null,
|
|
62
|
+
onUpload: null,
|
|
63
|
+
onComplete: null,
|
|
64
|
+
};
|
|
65
|
+
//合并参数
|
|
66
|
+
Object.assign(config, options);
|
|
67
|
+
//
|
|
68
|
+
const method = config.method.toUpperCase() || 'POST', methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
|
|
69
|
+
//创建XMLHttpRequest
|
|
70
|
+
let xhr = new XMLHttpRequest(),
|
|
71
|
+
//设置发送数据和预设请求头
|
|
72
|
+
requestData = null, headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'], removeHeader = () => {
|
|
73
|
+
if (headerContentType) {
|
|
74
|
+
delete config.headers['Content-Type'];
|
|
75
|
+
delete config.headers['content-type'];
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
if (!isEmpty(config.data)) {
|
|
79
|
+
let dataType = getDataType(config.data);
|
|
80
|
+
if (dataType === 'FormData') {
|
|
81
|
+
//如果是new FormData格式,直接相等
|
|
82
|
+
requestData = config.data;
|
|
83
|
+
// 不需要手动设置Content-Type,浏览器会自动设置
|
|
84
|
+
//config.contType = 'multipart/form-data';
|
|
85
|
+
removeHeader();
|
|
86
|
+
}
|
|
87
|
+
else if (dataType === 'Object') {
|
|
88
|
+
//如果是对象格式{name:'',age:''}
|
|
89
|
+
//并且此时已经设置了contType
|
|
90
|
+
if (!headerContentType) {
|
|
91
|
+
//如果未设置则默认设为如下contType
|
|
92
|
+
//Content-Type=application/x-www-form-urlencoded
|
|
93
|
+
/* for (let k in config.data) {
|
|
94
|
+
requestData += '&' + k + '=' + config.data[k];
|
|
95
|
+
} */
|
|
96
|
+
requestData = new URLSearchParams(config.data).toString();
|
|
97
|
+
//URLSearchParams.toString => `a=1&b=3`
|
|
98
|
+
//非get、head方法修正content-type
|
|
99
|
+
if (!methodsWithoutBody.includes(method)) {
|
|
100
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else if (headerContentType?.includes('application/json')) {
|
|
104
|
+
//Content-Type=application/json或contentType=application/json
|
|
105
|
+
requestData = JSON.stringify(config.data);
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
requestData = config.data;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
else if (dataType === 'String') {
|
|
112
|
+
//未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
|
|
113
|
+
if (!headerContentType || headerContentType.includes('urlencoded')) {
|
|
114
|
+
//如果是name=''&age=''字符串
|
|
115
|
+
//?name=''&age=''或&name=''&age=''统一去掉第一个&/?
|
|
116
|
+
requestData = cleanQueryString(config.data.trim());
|
|
117
|
+
//非get、head方法修正content-type
|
|
118
|
+
if (!methodsWithoutBody.includes(method) && !headerContentType) {
|
|
119
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
requestData = config.data;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
requestData = config.data;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
//设置超时时间
|
|
131
|
+
xhr.timeout = config.timeout;
|
|
132
|
+
// 响应类型
|
|
133
|
+
if (config.responseType) {
|
|
134
|
+
xhr.responseType = config.responseType;
|
|
135
|
+
}
|
|
136
|
+
//返回promise
|
|
137
|
+
const result = new Promise((resolve, reject) => {
|
|
138
|
+
//超时监听
|
|
139
|
+
const timeoutHandler = () => {
|
|
140
|
+
cleanup();
|
|
141
|
+
let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
|
|
142
|
+
//回调,status和content在此确认
|
|
143
|
+
config?.onTimeout?.(resp);
|
|
144
|
+
//reject只能接受一个参数
|
|
145
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
146
|
+
},
|
|
147
|
+
//报错监听
|
|
148
|
+
errorHandler = (resp) => {
|
|
149
|
+
//这几个错误来自xhr.onreadystatechange
|
|
150
|
+
if (resp.type === 'client-error') {
|
|
151
|
+
config?.onClientError?.({ ...context });
|
|
152
|
+
}
|
|
153
|
+
else if (resp.type === 'server-error') {
|
|
154
|
+
config?.onServerError?.({ ...context });
|
|
155
|
+
}
|
|
156
|
+
else if (resp.type === 'unknown-error') {
|
|
157
|
+
config?.onUnknownError?.({ ...context });
|
|
158
|
+
}
|
|
159
|
+
//此外还会有xhr.onerror的错误,所以需要统一使用onError监听
|
|
160
|
+
config?.onError?.(resp);
|
|
161
|
+
//reject只能接受一个参数
|
|
162
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
163
|
+
},
|
|
164
|
+
//取消监听
|
|
165
|
+
abortHandler = () => {
|
|
166
|
+
cleanup();
|
|
167
|
+
const resp = { ...context, status: xhr.status, type: 'abort' };
|
|
168
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
169
|
+
//回调,status和content在此确认
|
|
170
|
+
config?.onAbort?.(resp);
|
|
171
|
+
}, abortHandlerWithSignal = () => {
|
|
172
|
+
//先中止请求,防止触发其他 readystate 事件
|
|
173
|
+
xhr.abort();
|
|
174
|
+
abortHandler();
|
|
175
|
+
},
|
|
176
|
+
//成功监听
|
|
177
|
+
successHandler = (resp) => {
|
|
178
|
+
//成功回调
|
|
179
|
+
config?.onSuccess?.(resp);
|
|
180
|
+
//resolve只能接受一个参数
|
|
181
|
+
resolve(resp);
|
|
182
|
+
},
|
|
183
|
+
//统一处理abort
|
|
184
|
+
cleanup = () => {
|
|
185
|
+
// 如果使用了AbortSignal,则移除它的事件监听器
|
|
186
|
+
config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
|
|
187
|
+
// 移除各类事件监听器
|
|
188
|
+
config.onError && xhr.removeEventListener('error', errorHandler);
|
|
189
|
+
config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
|
|
190
|
+
// 解绑上传/下载进度事件
|
|
191
|
+
config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
|
|
192
|
+
config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
|
|
193
|
+
//销毁
|
|
194
|
+
xhr.onreadystatechange = null;
|
|
195
|
+
},
|
|
196
|
+
// Context object to track state
|
|
197
|
+
context = {
|
|
198
|
+
//原始xhr
|
|
199
|
+
xhr,
|
|
200
|
+
//发送的数据
|
|
201
|
+
data: requestData,
|
|
202
|
+
//可取消的函数
|
|
203
|
+
abort: abortHandler,
|
|
204
|
+
//xhr.status
|
|
205
|
+
status: '',
|
|
206
|
+
//响应的内容
|
|
207
|
+
content: null,
|
|
208
|
+
//0~4阶段编号
|
|
209
|
+
stage: 0,
|
|
210
|
+
//阶段名称
|
|
211
|
+
type: 'unset',
|
|
212
|
+
//上传和下载进度
|
|
213
|
+
progress: {}
|
|
214
|
+
},
|
|
215
|
+
//定义进度函数
|
|
216
|
+
progressHandler = (name, data, callback) => {
|
|
217
|
+
if (data.lengthComputable) {
|
|
218
|
+
const resp = { ...context, status: xhr.status }, ratio = data.loaded / data.total;
|
|
219
|
+
resp.progress = {
|
|
220
|
+
name,
|
|
221
|
+
loaded: data.loaded,
|
|
222
|
+
total: data.total,
|
|
223
|
+
timestamp: (new Date(data.timeStamp)).getTime(),
|
|
224
|
+
ratio,
|
|
225
|
+
percent: Math.round(ratio * 100),
|
|
226
|
+
};
|
|
227
|
+
callback?.(resp);
|
|
228
|
+
//到达100%执行complete
|
|
229
|
+
if (resp.progress.percent >= 100) {
|
|
230
|
+
resp.progress.percent = 100;
|
|
231
|
+
config?.onComplete?.(resp);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}, uploadProgressHandler = (data) => {
|
|
235
|
+
progressHandler('upload', data, (resp) => config.onUpload(resp));
|
|
236
|
+
}, downloadProgressHandler = (data) => {
|
|
237
|
+
progressHandler('download', data, (resp) => config.onDownload(resp));
|
|
238
|
+
};
|
|
239
|
+
//使用AbortSignal
|
|
240
|
+
if (config.signal) {
|
|
241
|
+
if (config.signal.aborted)
|
|
242
|
+
return abortHandlerWithSignal();
|
|
243
|
+
config.signal.addEventListener('abort', abortHandlerWithSignal);
|
|
244
|
+
}
|
|
245
|
+
//监听上传进度
|
|
246
|
+
config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
|
|
247
|
+
//监听下载进度
|
|
248
|
+
config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
|
|
249
|
+
// 事件监听器
|
|
250
|
+
config.onError && xhr.addEventListener('error', errorHandler);
|
|
251
|
+
config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
|
|
252
|
+
config.onAbort && xhr.addEventListener('abort', abortHandler);
|
|
253
|
+
// 手动触发 Created 状态
|
|
254
|
+
config.onCreated?.({ ...context, type: 'created' });
|
|
255
|
+
//状态判断
|
|
256
|
+
xhr.onreadystatechange = function () {
|
|
257
|
+
context.stage = xhr.readyState;
|
|
258
|
+
context.status = xhr.status;
|
|
259
|
+
const statusMap = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
|
|
260
|
+
//0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
|
|
261
|
+
if (xhr.readyState < 4) {
|
|
262
|
+
if (!xhr.readyState)
|
|
263
|
+
return;
|
|
264
|
+
context.type = statusMap[xhr.readyState];
|
|
265
|
+
config[`on${capitalize(context.type)}`]?.({ ...context });
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
//已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
|
|
269
|
+
cleanup();
|
|
270
|
+
const isInformation = xhr.status >= 100 && xhr.status < 200, isSuccess = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304, isRedirection = xhr.status >= 300 && xhr.status < 400, isClientError = xhr.status >= 400 && xhr.status < 500, isServerError = xhr.status >= 500 && xhr.status < 600;
|
|
271
|
+
//已经获得返回数据
|
|
272
|
+
if (isSuccess) {
|
|
273
|
+
if (!config.responseType || xhr.responseType === 'text') {
|
|
274
|
+
//可能返回字符串类型的对象,wordpress的REST API
|
|
275
|
+
let trim = xhr.responseText.trim(), content = '';
|
|
276
|
+
if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
|
|
277
|
+
//通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
|
|
278
|
+
try {
|
|
279
|
+
content = JSON.parse(trim);
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
console.warn('Malformed JSON detected, falling back to text.');
|
|
283
|
+
content = xhr.responseText;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
else if (/(<\/html>|<\/body>)/i.test(trim)) {
|
|
287
|
+
//请求了一个HTML页面
|
|
288
|
+
//返回文本类型DOMstring
|
|
289
|
+
let urlHash = getUrlHash(config.url);
|
|
290
|
+
content = getBodyHTML(trim, config.selector || urlHash);
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
//普通文本,不做任何处理
|
|
294
|
+
content = xhr.responseText;
|
|
295
|
+
}
|
|
296
|
+
//content=文本字符串/json
|
|
297
|
+
context.content = content;
|
|
298
|
+
}
|
|
299
|
+
else {
|
|
300
|
+
//content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
|
|
301
|
+
context.content = xhr.response;
|
|
302
|
+
}
|
|
303
|
+
context.type = 'success';
|
|
304
|
+
successHandler({ ...context });
|
|
305
|
+
}
|
|
306
|
+
else {
|
|
307
|
+
//失败回调
|
|
308
|
+
context.content = xhr.response;
|
|
309
|
+
context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
|
|
310
|
+
//
|
|
311
|
+
if (isInformation) {
|
|
312
|
+
config?.onInformation?.({ ...context });
|
|
313
|
+
}
|
|
314
|
+
else if (isRedirection) {
|
|
315
|
+
config?.onRedirection?.({ ...context });
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
errorHandler({ ...context });
|
|
319
|
+
}
|
|
320
|
+
//
|
|
321
|
+
config?.onFailure?.({ ...context });
|
|
322
|
+
}
|
|
323
|
+
config?.onFinish?.({ ...context });
|
|
324
|
+
};
|
|
325
|
+
//发送异步请求
|
|
326
|
+
let openParams = [method, config.url, config.async];
|
|
327
|
+
if (methodsWithoutBody.includes(method)) {
|
|
328
|
+
// 拼接url => xxx.com?a=0&b=1#hello
|
|
329
|
+
const url = buildUrl({
|
|
330
|
+
url: config.url,
|
|
331
|
+
data: requestData,
|
|
332
|
+
cacheBustKey: config.cacheBustKey,
|
|
333
|
+
appendCacheBust: true,
|
|
334
|
+
});
|
|
335
|
+
openParams = [method, url, config.async];
|
|
336
|
+
}
|
|
337
|
+
//设置xhr其他字段
|
|
338
|
+
for (let k in config.xhrFields) {
|
|
339
|
+
config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
|
|
340
|
+
}
|
|
341
|
+
//与服务器建立连接
|
|
342
|
+
xhr.open(...openParams);
|
|
343
|
+
//有则设置,仅跳过空内容
|
|
344
|
+
for (let k in config.headers) {
|
|
345
|
+
config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
|
|
346
|
+
}
|
|
347
|
+
config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
|
|
348
|
+
//发送请求,get和head不需要发送数据
|
|
349
|
+
xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
|
|
350
|
+
//open和send阶段已经是异步了,无法使用try+catch捕获错误
|
|
351
|
+
});
|
|
352
|
+
//绑定xhr和abort
|
|
353
|
+
result.xhr = xhr;
|
|
354
|
+
result.abort = () => xhr.abort();
|
|
355
|
+
return result;
|
|
356
|
+
};
|
|
357
|
+
// Static Helper Methods
|
|
358
|
+
//get、head、trace是不需要发送数据的,data将被转为url参数处理
|
|
359
|
+
['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
|
|
360
|
+
ajax[method] = (url, data, options = { url: '' }) => ajax({ ...options, method, url, data });
|
|
361
|
+
});
|
|
362
|
+
ajax.all = (requests) => Promise.all(requests.map(ajax));
|
|
363
|
+
export default ajax;
|