@codady/utils 0.0.38 → 0.0.40
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 +37 -0
- package/dist/utils.cjs.js +576 -24
- package/dist/utils.cjs.min.js +3 -3
- package/dist/utils.esm.js +576 -24
- package/dist/utils.esm.min.js +3 -3
- package/dist/utils.umd.js +576 -24
- package/dist/utils.umd.min.js +3 -3
- package/dist.zip +0 -0
- package/examples/ajax-download.html +94 -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/ajax-signal.html +91 -0
- package/examples/ajax-timeout.html +85 -0
- package/examples/buildUrl.html +99 -0
- package/examples/getUrlHash.html +71 -0
- package/examples/stringToEncodings-collision-test-registry.html +117 -0
- package/examples/stringToEncodings-collision-test.html +71 -0
- package/examples/stringToEncodings.html +138 -0
- package/examples/unicodeToEncodings.html +195 -0
- package/modules.js +17 -1
- package/modules.ts +17 -1
- package/package.json +1 -1
- package/src/ajax.js +380 -0
- package/src/ajax.ts +470 -0
- package/src/buildUrl.js +64 -0
- package/src/buildUrl.ts +86 -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/stringToEncodings.js +56 -0
- package/src/stringToEncodings.ts +110 -0
- package/src/unicodeToEncodings.js +51 -0
- package/src/unicodeToEncodings.ts +55 -0
- package/src/arrayMutableMethods - /345/211/257/346/234/254.js" +0 -5
- package/src/comma - /345/211/257/346/234/254.js" +0 -2
- package/src/deepCloneToJSON - /345/211/257/346/234/254.js" +0 -47
- package/src/deepMergeMaps - /345/211/257/346/234/254.js" +0 -78
- package/src/escapeHTML - /345/211/257/346/234/254.js" +0 -29
- package/src/getDataType - /345/211/257/346/234/254.js" +0 -38
- package/src/isEmpty - /345/211/257/346/234/254.js" +0 -45
- package/src/mapMutableMethods - /345/211/257/346/234/254.js" +0 -5
- package/src/setMutableMethods - /345/211/257/346/234/254.js" +0 -5
- package/src/wrapMap - /345/211/257/346/234/254.js" +0 -119
package/modules.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Last modified: 2026/
|
|
2
|
+
* Last modified: 2026/02/05 17:00:27
|
|
3
3
|
*/
|
|
4
4
|
'use strict';
|
|
5
5
|
import deepClone from './src/deepClone';
|
|
@@ -41,6 +41,14 @@ import escapeHTML from './src/escapeHTML';
|
|
|
41
41
|
import escapeRegexMaps from './src/escapeRegexMaps';
|
|
42
42
|
import escapeCharsMaps from './src/escapeCharsMaps';
|
|
43
43
|
import toSingleLine from './src/toSingleLine';
|
|
44
|
+
import getBodyHTML from './src/getBodyHTML';
|
|
45
|
+
import getUrlHash from './src/getUrlHash';
|
|
46
|
+
import buildUrl from './src/buildUrl';
|
|
47
|
+
import ajax from './src/ajax';
|
|
48
|
+
import capitalize from './src/capitalize';
|
|
49
|
+
import cleanQueryString from './src/cleanQueryString';
|
|
50
|
+
import stringToEncodings from './src/stringToEncodings';
|
|
51
|
+
import unicodeToEncodings from './src/unicodeToEncodings';
|
|
44
52
|
const utils = {
|
|
45
53
|
//executeStr,
|
|
46
54
|
getDataType,
|
|
@@ -84,5 +92,13 @@ const utils = {
|
|
|
84
92
|
escapeHTML,
|
|
85
93
|
toSingleLine,
|
|
86
94
|
renderTpl,
|
|
95
|
+
getBodyHTML,
|
|
96
|
+
getUrlHash,
|
|
97
|
+
buildUrl,
|
|
98
|
+
ajax,
|
|
99
|
+
capitalize,
|
|
100
|
+
cleanQueryString,
|
|
101
|
+
stringToEncodings,
|
|
102
|
+
unicodeToEncodings,
|
|
87
103
|
};
|
|
88
104
|
export default utils;
|
package/modules.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Last modified: 2026/
|
|
2
|
+
* Last modified: 2026/02/05 17:00:27
|
|
3
3
|
*/
|
|
4
4
|
'use strict'
|
|
5
5
|
import deepClone from './src/deepClone';
|
|
@@ -48,6 +48,14 @@ import escapeHTML from './src/escapeHTML';
|
|
|
48
48
|
import escapeRegexMaps from './src/escapeRegexMaps';
|
|
49
49
|
import escapeCharsMaps from './src/escapeCharsMaps';
|
|
50
50
|
import toSingleLine from './src/toSingleLine';
|
|
51
|
+
import getBodyHTML from './src/getBodyHTML';
|
|
52
|
+
import getUrlHash from './src/getUrlHash';
|
|
53
|
+
import buildUrl from './src/buildUrl';
|
|
54
|
+
import ajax from './src/ajax';
|
|
55
|
+
import capitalize from './src/capitalize';
|
|
56
|
+
import cleanQueryString from './src/cleanQueryString';
|
|
57
|
+
import stringToEncodings from './src/stringToEncodings';
|
|
58
|
+
import unicodeToEncodings from './src/unicodeToEncodings';
|
|
51
59
|
|
|
52
60
|
const utils = {
|
|
53
61
|
//executeStr,
|
|
@@ -92,6 +100,14 @@ const utils = {
|
|
|
92
100
|
escapeHTML,
|
|
93
101
|
toSingleLine,
|
|
94
102
|
renderTpl,
|
|
103
|
+
getBodyHTML,
|
|
104
|
+
getUrlHash,
|
|
105
|
+
buildUrl,
|
|
106
|
+
ajax,
|
|
107
|
+
capitalize,
|
|
108
|
+
cleanQueryString,
|
|
109
|
+
stringToEncodings,
|
|
110
|
+
unicodeToEncodings,
|
|
95
111
|
|
|
96
112
|
};
|
|
97
113
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codady/utils",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.40",
|
|
4
4
|
"author": "AXUI Development Team",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "This is a set of general-purpose JavaScript utility functions developed by the AXUI team. All functions are pure and do not involve CSS or other third-party libraries. They are suitable for any web front-end environment.",
|
package/src/ajax.js
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since Last modified: 2026/01/20 18:14:18
|
|
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
|
+
precision: 2,
|
|
41
|
+
//
|
|
42
|
+
onAbort: null,
|
|
43
|
+
onTimeout: null,
|
|
44
|
+
//
|
|
45
|
+
onBeforeSend: null,
|
|
46
|
+
//
|
|
47
|
+
onCreated: null,
|
|
48
|
+
onOpened: null,
|
|
49
|
+
onHeadersReceived: null,
|
|
50
|
+
onLoading: null,
|
|
51
|
+
//
|
|
52
|
+
onSuccess: null,
|
|
53
|
+
onFailure: null,
|
|
54
|
+
onInformation: null,
|
|
55
|
+
onRedirection: null,
|
|
56
|
+
onClientError: null,
|
|
57
|
+
onServerError: null,
|
|
58
|
+
onUnknownError: null,
|
|
59
|
+
onError: null,
|
|
60
|
+
onFinish: null,
|
|
61
|
+
//
|
|
62
|
+
onDownload: null,
|
|
63
|
+
onUpload: null,
|
|
64
|
+
onComplete: null,
|
|
65
|
+
};
|
|
66
|
+
//合并参数
|
|
67
|
+
Object.assign(config, options);
|
|
68
|
+
//
|
|
69
|
+
const method = config.method.toUpperCase() || 'POST', methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
|
|
70
|
+
//创建XMLHttpRequest
|
|
71
|
+
let xhr = new XMLHttpRequest(),
|
|
72
|
+
//设置发送数据和预设请求头
|
|
73
|
+
requestData = null, headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'], removeHeader = () => {
|
|
74
|
+
if (headerContentType) {
|
|
75
|
+
delete config.headers['Content-Type'];
|
|
76
|
+
delete config.headers['content-type'];
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
if (!isEmpty(config.data)) {
|
|
80
|
+
let dataType = getDataType(config.data);
|
|
81
|
+
if (dataType === 'FormData') {
|
|
82
|
+
//如果是new FormData格式,直接相等
|
|
83
|
+
requestData = config.data;
|
|
84
|
+
// 不需要手动设置Content-Type,浏览器会自动设置
|
|
85
|
+
//config.contType = 'multipart/form-data';
|
|
86
|
+
removeHeader();
|
|
87
|
+
}
|
|
88
|
+
else if (dataType === 'Object') {
|
|
89
|
+
//如果是对象格式{name:'',age:''}
|
|
90
|
+
//并且此时已经设置了contType
|
|
91
|
+
if (!headerContentType) {
|
|
92
|
+
//如果未设置则默认设为如下contType
|
|
93
|
+
//Content-Type=application/x-www-form-urlencoded
|
|
94
|
+
/* for (let k in config.data) {
|
|
95
|
+
requestData += '&' + k + '=' + config.data[k];
|
|
96
|
+
} */
|
|
97
|
+
requestData = new URLSearchParams(config.data).toString();
|
|
98
|
+
//URLSearchParams.toString => `a=1&b=3`
|
|
99
|
+
//非get、head方法修正content-type
|
|
100
|
+
if (!methodsWithoutBody.includes(method)) {
|
|
101
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
else if (headerContentType?.includes('application/json')) {
|
|
105
|
+
//Content-Type=application/json或contentType=application/json
|
|
106
|
+
requestData = JSON.stringify(config.data);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
requestData = config.data;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
else if (dataType === 'String') {
|
|
113
|
+
//未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
|
|
114
|
+
if (!headerContentType || headerContentType.includes('urlencoded')) {
|
|
115
|
+
//如果是name=''&age=''字符串
|
|
116
|
+
//?name=''&age=''或&name=''&age=''统一去掉第一个&/?
|
|
117
|
+
requestData = cleanQueryString(config.data.trim());
|
|
118
|
+
//非get、head方法修正content-type
|
|
119
|
+
if (!methodsWithoutBody.includes(method) && !headerContentType) {
|
|
120
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
requestData = config.data;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
requestData = config.data;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
//设置超时时间
|
|
132
|
+
xhr.timeout = config.timeout;
|
|
133
|
+
// 响应类型
|
|
134
|
+
if (config.responseType) {
|
|
135
|
+
xhr.responseType = config.responseType;
|
|
136
|
+
}
|
|
137
|
+
//返回promise
|
|
138
|
+
const result = new Promise((resolve, reject) => {
|
|
139
|
+
//超时监听
|
|
140
|
+
const timeoutHandler = () => {
|
|
141
|
+
cleanup();
|
|
142
|
+
let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
|
|
143
|
+
//回调,status和content在此确认
|
|
144
|
+
config?.onTimeout?.(resp);
|
|
145
|
+
//reject只能接受一个参数
|
|
146
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
147
|
+
//超时也是不能获得数据的行为,定义为failure
|
|
148
|
+
config?.onFailure?.(resp);
|
|
149
|
+
//timeout会经过onreadystatechange,但是被及时的return了,所以这里多加一行
|
|
150
|
+
config?.onFinish?.(resp);
|
|
151
|
+
},
|
|
152
|
+
//报错监听
|
|
153
|
+
errorHandler = (resp) => {
|
|
154
|
+
//这几个错误来自xhr.onreadystatechange
|
|
155
|
+
if (resp.type === 'client-error') {
|
|
156
|
+
config?.onClientError?.({ ...context });
|
|
157
|
+
}
|
|
158
|
+
else if (resp.type === 'server-error') {
|
|
159
|
+
config?.onServerError?.({ ...context });
|
|
160
|
+
}
|
|
161
|
+
else if (resp.type === 'unknown-error') {
|
|
162
|
+
config?.onUnknownError?.({ ...context });
|
|
163
|
+
}
|
|
164
|
+
//此外还会有xhr.onerror的错误,所以需要统一使用onError监听
|
|
165
|
+
config?.onError?.(resp);
|
|
166
|
+
//reject只能接受一个参数
|
|
167
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
168
|
+
},
|
|
169
|
+
//取消监听
|
|
170
|
+
abortHandler = () => {
|
|
171
|
+
cleanup();
|
|
172
|
+
const resp = { ...context, status: xhr.status, type: 'abort' };
|
|
173
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
174
|
+
//回调,status和content在此确认
|
|
175
|
+
config?.onAbort?.(resp);
|
|
176
|
+
//abort行为不会经过onreadystatechange,这里需要多这一行以表示xhr的完成(结束)
|
|
177
|
+
config?.onFinish?.(resp);
|
|
178
|
+
}, abortHandlerWithSignal = () => {
|
|
179
|
+
//先中止请求,防止触发其他 readystate 事件
|
|
180
|
+
xhr.abort();
|
|
181
|
+
abortHandler();
|
|
182
|
+
},
|
|
183
|
+
//成功监听
|
|
184
|
+
successHandler = (resp) => {
|
|
185
|
+
//成功回调
|
|
186
|
+
config?.onSuccess?.(resp);
|
|
187
|
+
//resolve只能接受一个参数
|
|
188
|
+
resolve(resp);
|
|
189
|
+
},
|
|
190
|
+
//统一处理abort
|
|
191
|
+
cleanup = () => {
|
|
192
|
+
// 如果使用了AbortSignal,则移除它的事件监听器
|
|
193
|
+
config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
|
|
194
|
+
// 移除各类事件监听器
|
|
195
|
+
config.onError && xhr.removeEventListener('error', errorHandler);
|
|
196
|
+
config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
|
|
197
|
+
// 解绑上传/下载进度事件
|
|
198
|
+
config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
|
|
199
|
+
config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
|
|
200
|
+
//销毁
|
|
201
|
+
xhr.onreadystatechange = null;
|
|
202
|
+
},
|
|
203
|
+
// Context object to track state
|
|
204
|
+
context = {
|
|
205
|
+
//原始xhr
|
|
206
|
+
xhr,
|
|
207
|
+
//发送的数据
|
|
208
|
+
data: requestData,
|
|
209
|
+
//可取消的函数
|
|
210
|
+
abort: abortHandler,
|
|
211
|
+
//xhr.status
|
|
212
|
+
status: '',
|
|
213
|
+
//响应的内容
|
|
214
|
+
content: null,
|
|
215
|
+
//0~4阶段编号
|
|
216
|
+
stage: 0,
|
|
217
|
+
//阶段名称
|
|
218
|
+
type: 'unset',
|
|
219
|
+
//上传和下载进度
|
|
220
|
+
progress: {}
|
|
221
|
+
}, getProgressValues = (ratio) => {
|
|
222
|
+
let text = (ratio * 100).toFixed(config.precision);
|
|
223
|
+
return { percent: parseFloat(text), text };
|
|
224
|
+
},
|
|
225
|
+
//定义进度函数
|
|
226
|
+
progressHandler = (name, data, callback) => {
|
|
227
|
+
if (data.lengthComputable) {
|
|
228
|
+
const resp = { ...context, status: xhr.status }, ratio = data.loaded / data.total, { percent, text } = getProgressValues(ratio);
|
|
229
|
+
resp.progress = {
|
|
230
|
+
name,
|
|
231
|
+
loaded: data.loaded,
|
|
232
|
+
total: data.total,
|
|
233
|
+
timestamp: (new Date(data.timeStamp)).getTime(),
|
|
234
|
+
ratio,
|
|
235
|
+
percent,
|
|
236
|
+
text,
|
|
237
|
+
};
|
|
238
|
+
callback?.(resp);
|
|
239
|
+
if (ratio >= 1) {
|
|
240
|
+
Object.assign(resp.progress, getProgressValues(1));
|
|
241
|
+
config?.onComplete?.(resp);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}, uploadProgressHandler = (data) => {
|
|
245
|
+
progressHandler('upload', data, (resp) => config.onUpload(resp));
|
|
246
|
+
}, downloadProgressHandler = (data) => {
|
|
247
|
+
progressHandler('download', data, (resp) => config.onDownload(resp));
|
|
248
|
+
};
|
|
249
|
+
//使用AbortSignal
|
|
250
|
+
if (config.signal) {
|
|
251
|
+
if (config.signal.aborted)
|
|
252
|
+
return abortHandlerWithSignal();
|
|
253
|
+
config.signal.addEventListener('abort', abortHandlerWithSignal);
|
|
254
|
+
}
|
|
255
|
+
//监听上传进度
|
|
256
|
+
config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
|
|
257
|
+
//监听下载进度
|
|
258
|
+
config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
|
|
259
|
+
// 事件监听器
|
|
260
|
+
config.onError && xhr.addEventListener('error', errorHandler);
|
|
261
|
+
config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
|
|
262
|
+
config.onAbort && xhr.addEventListener('abort', abortHandler);
|
|
263
|
+
// 手动触发 Created 状态
|
|
264
|
+
config.onCreated?.({ ...context, type: 'created' });
|
|
265
|
+
//状态判断
|
|
266
|
+
xhr.onreadystatechange = function () {
|
|
267
|
+
context.stage = xhr.readyState;
|
|
268
|
+
context.status = xhr.status;
|
|
269
|
+
const statusMap = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
|
|
270
|
+
//0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
|
|
271
|
+
if (xhr.readyState < 4) {
|
|
272
|
+
if (!xhr.readyState)
|
|
273
|
+
return;
|
|
274
|
+
context.type = statusMap[xhr.readyState];
|
|
275
|
+
config[`on${capitalize(context.type)}`]?.({ ...context });
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
//tiemeout事件也会执行这里,此时需要让它触发onTimeout事件
|
|
279
|
+
//abort和timeout行为的status是0
|
|
280
|
+
//不过abort行为不会执行到这里
|
|
281
|
+
if (xhr.status === 0 && context.type !== 'abort') {
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
//已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
|
|
285
|
+
cleanup();
|
|
286
|
+
//根据状态码判断响应结果
|
|
287
|
+
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;
|
|
288
|
+
//已经获得返回数据
|
|
289
|
+
if (isSuccess) {
|
|
290
|
+
if (!config.responseType || xhr.responseType === 'text') {
|
|
291
|
+
//可能返回字符串类型的对象,wordpress的REST API
|
|
292
|
+
let trim = xhr.responseText.trim(), content = '';
|
|
293
|
+
if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
|
|
294
|
+
//通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
|
|
295
|
+
try {
|
|
296
|
+
content = JSON.parse(trim);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
console.warn('Malformed JSON detected, falling back to text.');
|
|
300
|
+
content = xhr.responseText;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
else if (/(<\/html>|<\/body>)/i.test(trim)) {
|
|
304
|
+
//请求了一个HTML页面
|
|
305
|
+
//返回文本类型DOMstring
|
|
306
|
+
let urlHash = getUrlHash(config.url);
|
|
307
|
+
content = getBodyHTML(trim, config.selector || urlHash);
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
//普通文本,不做任何处理
|
|
311
|
+
content = xhr.responseText;
|
|
312
|
+
}
|
|
313
|
+
//content=文本字符串/json
|
|
314
|
+
context.content = content;
|
|
315
|
+
}
|
|
316
|
+
else {
|
|
317
|
+
//content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
|
|
318
|
+
context.content = xhr.response;
|
|
319
|
+
}
|
|
320
|
+
context.type = 'success';
|
|
321
|
+
successHandler({ ...context });
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
//失败回调
|
|
325
|
+
context.content = xhr.response;
|
|
326
|
+
context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
|
|
327
|
+
//
|
|
328
|
+
if (isInformation) {
|
|
329
|
+
config?.onInformation?.({ ...context });
|
|
330
|
+
}
|
|
331
|
+
else if (isRedirection) {
|
|
332
|
+
config?.onRedirection?.({ ...context });
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
errorHandler({ ...context });
|
|
336
|
+
}
|
|
337
|
+
//
|
|
338
|
+
config?.onFailure?.({ ...context });
|
|
339
|
+
}
|
|
340
|
+
config?.onFinish?.({ ...context });
|
|
341
|
+
};
|
|
342
|
+
//发送异步请求
|
|
343
|
+
let openParams = [method, config.url, config.async];
|
|
344
|
+
if (methodsWithoutBody.includes(method)) {
|
|
345
|
+
// 拼接url => xxx.com?a=0&b=1#hello
|
|
346
|
+
const url = buildUrl({
|
|
347
|
+
url: config.url,
|
|
348
|
+
data: requestData,
|
|
349
|
+
cacheBustKey: config.cacheBustKey,
|
|
350
|
+
appendCacheBust: true,
|
|
351
|
+
});
|
|
352
|
+
openParams = [method, url, config.async];
|
|
353
|
+
}
|
|
354
|
+
//设置xhr其他字段
|
|
355
|
+
for (let k in config.xhrFields) {
|
|
356
|
+
config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
|
|
357
|
+
}
|
|
358
|
+
//与服务器建立连接
|
|
359
|
+
xhr.open(...openParams);
|
|
360
|
+
//有则设置,仅跳过空内容
|
|
361
|
+
for (let k in config.headers) {
|
|
362
|
+
config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
|
|
363
|
+
}
|
|
364
|
+
config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
|
|
365
|
+
//发送请求,get和head不需要发送数据
|
|
366
|
+
xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
|
|
367
|
+
//open和send阶段已经是异步了,无法使用try+catch捕获错误
|
|
368
|
+
});
|
|
369
|
+
//绑定xhr和abort
|
|
370
|
+
result.xhr = xhr;
|
|
371
|
+
result.abort = () => xhr.abort();
|
|
372
|
+
return result;
|
|
373
|
+
};
|
|
374
|
+
// Static Helper Methods
|
|
375
|
+
//get、head、trace是不需要发送数据的,data将被转为url参数处理
|
|
376
|
+
['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
|
|
377
|
+
ajax[method] = (url, data, options = { url: '' }) => ajax({ ...options, method, url, data });
|
|
378
|
+
});
|
|
379
|
+
ajax.all = (requests) => Promise.all(requests.map(ajax));
|
|
380
|
+
export default ajax;
|