@ajaxjs/util 1.1.3 → 1.2.1

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/dist/index.umd.js CHANGED
@@ -1,57 +1,121 @@
1
1
  (function (global, factory) {
2
2
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
3
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.index = global.index || {}, global.index.umd = global.index.umd || {}, global.index.umd.js = {})));
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.AjaxjsUtil = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
+ function getQueryParam(variable, isParent = false) {
8
+ const query = (isParent ? parent.location : window.location).search.substring(1);
9
+ const vars = query.split("&");
10
+ for (let i = 0; i < vars.length; i++) {
11
+ const pair = vars[i].split("=");
12
+ if (pair[0] == variable)
13
+ return pair[1];
14
+ }
15
+ return null;
16
+ }
7
17
  /**
8
- * 获取某个 Cookie
18
+ * 函数节流
9
19
  *
10
- * @param name 键名称
11
- * @returns
20
+ * @author https://www.cnblogs.com/moqiutao/p/6875955.html
21
+ * @param fn
22
+ * @param delay
23
+ * @param mustRunDelay
12
24
  */
13
- function getCookie(name) {
14
- let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
15
- // @ts-ignore
16
- if (arr = document.cookie.match(reg))
17
- return unescape(arr[2]);
18
- else
19
- return null;
25
+ function throttle(fn, delay, mustRunDelay) {
26
+ let timer, t_start;
27
+ return function () {
28
+ let t_curr = +new Date();
29
+ window.clearTimeout(timer);
30
+ if (!t_start)
31
+ t_start = t_curr;
32
+ if (t_curr - t_start >= mustRunDelay) {
33
+ fn.apply(this, arguments);
34
+ t_start = t_curr;
35
+ }
36
+ else {
37
+ let args = arguments;
38
+ timer = window.setTimeout(() => fn.apply(this, args), delay);
39
+ }
40
+ };
20
41
  }
21
42
  /**
22
- * 设置某个 Cookie
43
+ * 并行和串行任务
23
44
  *
24
- * @param name 键名称
25
- * @param value 值
45
+ * @author https://segmentfault.com/a/1190000013265925
46
+ * @param arr
47
+ * @param finnaly
26
48
  */
27
- function setCookie(name, value) {
28
- let days = 2, exp = new Date();
29
- exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
49
+ function parallel(arr, _finally) {
50
+ let fn, index = 0;
30
51
  // @ts-ignore
31
- document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
52
+ let statusArr = Array(arr.length).fill().map(() => ({ isActive: false, data: null }));
53
+ let isFinished = () => statusArr.every((item) => item.isActive === true);
54
+ let resolve = function (index) {
55
+ return function (data) {
56
+ statusArr[index].data = data;
57
+ statusArr[index].isActive = true;
58
+ let isFinish = isFinished();
59
+ if (isFinish) {
60
+ let datas = statusArr.map((item) => item.data);
61
+ _finally(datas);
62
+ }
63
+ };
64
+ };
65
+ while ((fn = arr.shift())) {
66
+ fn(resolve(index)); // 给 resolve 函数追加参数,可以使用 bind 函数实现,这里使用了柯里化
67
+ index++;
68
+ }
32
69
  }
33
70
  /**
34
- * 清空 Cookie
71
+ * 通用的打开下载对话框方法,没有测试过具体兼容性
72
+ * https://www.cnblogs.com/liuxianan/p/js-download.html
73
+ *
74
+ * ref 这应该是你见过的最全前端下载总结 https://juejin.cn/post/6844903763359039501
75
+ *
76
+ * @param url 下载地址,也可以是一个blob对象,必选
77
+ * @param saveName 保存文件名,可选
35
78
  */
36
- function delCookie() {
37
- let keys = document.cookie.match(/[^ =;]+(?==)/g);
38
- if (keys) {
39
- let date = new Date(0).toUTCString();
40
- for (let i = keys.length; i--;) {
41
- document.cookie = keys[i] + '=0;path=/;expires=' + date; // 清除当前域名下的,例如:m.ratingdog.cn
42
- document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + date; // 清除当前域名下的,例如 .m.ratingdog.cn
43
- document.cookie = keys[i] + '=0;path=/;domain=' + location.host + ';expires=' + date; // 清除一级域名下的或指定的,例如 .ratingdog.cn
79
+ function openDownloadDialog(url, saveName) {
80
+ if (typeof url == 'object' && url instanceof Blob)
81
+ url = URL.createObjectURL(url); // 创建blob地址
82
+ const aLink = document.createElement('a');
83
+ aLink.href = url;
84
+ aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
85
+ let event;
86
+ if (window.MouseEvent)
87
+ event = new MouseEvent('click');
88
+ else {
89
+ event = document.createEvent('MouseEvents');
90
+ event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
91
+ }
92
+ aLink.dispatchEvent(event);
93
+ }
94
+ function myHTMLInclude() {
95
+ let a, file, xhttp;
96
+ const z = document.getElementsByTagName("*");
97
+ for (let i = 0; i < z.length; i++) {
98
+ if (z[i].getAttribute("w3-include-html")) {
99
+ a = z[i].cloneNode(false);
100
+ file = z[i].getAttribute("w3-include-html");
101
+ xhttp = new XMLHttpRequest();
102
+ xhttp.onreadystatechange = function () {
103
+ if (xhttp.readyState == 4 && xhttp.status == 200) {
104
+ a.removeAttribute("w3-include-html");
105
+ a.innerHTML = xhttp.responseText;
106
+ // @ts-ignore
107
+ z[i].parentNode.replaceChild(a, z[i]);
108
+ myHTMLInclude();
109
+ }
110
+ };
111
+ if (file) {
112
+ xhttp.open("GET", file, false);
113
+ xhttp.send();
114
+ }
115
+ return;
44
116
  }
45
117
  }
46
118
  }
47
-
48
- var cookies = /*#__PURE__*/Object.freeze({
49
- __proto__: null,
50
- delCookie: delCookie,
51
- getCookie: getCookie,
52
- setCookie: setCookie
53
- });
54
-
55
119
  /**
56
120
  * 向父级元素递归搜索
57
121
  *
@@ -74,56 +138,48 @@
74
138
  }
75
139
  return null;
76
140
  }
77
- /**
78
- * 加载脚本
79
- *
80
- * @param url 脚本地址
81
- * @param id 脚本元素 id,可选的
82
- * @param cb 回调函数,可选的
83
- */
84
- function loadScript(url, id, cb) {
85
- let script = document.createElement("script");
86
- script.src = url;
87
- if (cb)
88
- script.onload = cb;
89
- if (id)
90
- script.id = id;
91
- document.getElementsByTagName("head")[0].appendChild(script);
92
- }
93
141
 
94
- var dom = /*#__PURE__*/Object.freeze({
142
+ var utils = /*#__PURE__*/Object.freeze({
95
143
  __proto__: null,
96
- loadScript: loadScript,
144
+ getQueryParam: getQueryParam,
145
+ myHTMLInclude: myHTMLInclude,
146
+ openDownloadDialog: openDownloadDialog,
147
+ parallel: parallel,
148
+ throttle: throttle,
97
149
  up: up
98
150
  });
99
151
 
100
152
  /**
101
- * 通用工具类
102
- */
103
- /**
104
- * 是否调试模式中
153
+ * 格式化日期时间
105
154
  *
106
- * 打包成组件之后不能用
155
+ * @param {string} format 日期格式化模板
156
+ * @returns {string} 格式化后的日期字符串
157
+ * @this {Date} 调用此方法的Date对象
158
+ * @example
159
+ * // 返回类似 "2023-12-25 14:30:00"
160
+ * new Date().format("yyyy-MM-dd hh:mm:ss");
161
+ * // 返回类似 "23-12-25"
162
+ * new Date().format("yy-MM-dd");
163
+ * // 返回类似 "2023年12月25日"
164
+ * new Date().format("yyyy年MM月dd日");
107
165
  *
108
- * @returns
166
+ * 格式化模板说明:
167
+ * - yyyy: 四位年份
168
+ * - yy: 两位年份
169
+ * - MM: 两位月份(01-12)
170
+ * - M: 一位月份(1-12)
171
+ * - dd: 两位日期(01-31)
172
+ * - d: 一位日期(1-31)
173
+ * - hh: 两位小时(00-23)
174
+ * - h: 一位小时(0-23)
175
+ * - mm: 两位分钟(00-59)
176
+ * - m: 一位分钟(0-59)
177
+ * - ss: 两位秒钟(00-59)
178
+ * - s: 一位秒钟(0-59)
179
+ * - q: 季度(1-4)
180
+ * - S: 毫秒(000-999)
109
181
  */
110
- function isDebug() {
111
- // @ts-ignore
112
- return process.env.NODE_ENV === 'development';
113
- }
114
- function isDev() {
115
- let currentHostname = window.location.hostname;
116
- // 判断主机名是否是内网地址
117
- return (currentHostname.startsWith('192.168.') || currentHostname.startsWith('10.') || currentHostname === 'localhost');
118
- }
119
- /**
120
- * 日期格式化。详见博客文章:http://blog.csdn.net/zhangxin09/archive/2011/01/01/6111294.aspx
121
- * e.g: new Date().format("yyyy-MM-dd hh:mm:ss")
122
- *
123
- * @param {String} format
124
- * @return {String}
125
- */
126
- function dateFormat(format) {
182
+ function formatDate(format) {
127
183
  let $1, o = {
128
184
  "M+": this.getMonth() + 1, // 月份,从0开始算
129
185
  "d+": this.getDate(), // 日期
@@ -134,13 +190,15 @@
134
190
  "q+": Math.floor((this.getMonth() + 3) / 3),
135
191
  "S": this.getMilliseconds() // 千秒
136
192
  };
137
- if (/(y+)/.test(format))
138
- // @ts-ignore
139
- $1 = RegExp.$1, format = format.replace($1, String(this.getFullYear()).substr(4 - $1));
140
193
  let key, value;
194
+ if (/(y+)/.test(format)) {
195
+ $1 = RegExp.$1,
196
+ format = format.replace($1, String(this.getFullYear()).substr(4 - $1));
197
+ }
141
198
  for (key in o) { // 如果没有指定该参数,则子字符串将延续到 stringvar 的最后。
142
199
  if (new RegExp("(" + key + ")").test(format)) {
143
200
  $1 = RegExp.$1,
201
+ // @ts-ignore
144
202
  value = String(o[key]),
145
203
  value = $1.length == 1 ? value : ("00" + value).substr(value.length),
146
204
  format = format.replace($1, value);
@@ -150,387 +208,107 @@
150
208
  }
151
209
  /**
152
210
  * 日期格式化
153
- * @author meizz
154
- * @param date 日期,必须为 Date 类型
155
- * @param fmt 格式模板
156
- * @returns 格式化后的字符串
157
- */
158
- function dateFormat2(date, fmt) {
159
- let o = {
160
- "M+": date.getMonth() + 1, // 月份
161
- "d+": date.getDate(), // 日
162
- "h+": date.getHours(), // 小时
163
- "m+": date.getMinutes(), // 分
164
- "s+": date.getSeconds(), // 秒
165
- "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
166
- "S": date.getMilliseconds() // 毫秒
167
- };
168
- if (/(y+)/.test(fmt))
169
- fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
170
- for (var k in o)
171
- if (new RegExp("(" + k + ")").test(fmt)) {
172
- let obj = (RegExp.$1.length == 1) ? o[k] : ("00" + o[k]).substr(("" + o[k]).length);
173
- // @ts-ignore
174
- fmt = fmt.replace(RegExp.$1, obj);
175
- }
176
- return fmt;
177
- }
178
- /**
179
- * 并行和串行任务
180
211
  *
181
- * @author https://segmentfault.com/a/1190000013265925
182
- * @param arr
183
- * @param finnaly
212
+ * @param {date}
213
+ * @param {string} format 日期格式化模板
214
+ * @returns {string} 格式化后的日期字符串
184
215
  */
185
- function parallel(arr, _finally) {
186
- let fn, index = 0;
187
- // @ts-ignore
188
- let statusArr = Array(arr.length).fill().map(() => ({ isActive: false, data: null }));
189
- let isFinished = function () {
190
- return statusArr.every((item) => item.isActive === true);
191
- };
192
- let resolve = function (index) {
193
- return function (data) {
194
- statusArr[index].data = data;
195
- statusArr[index].isActive = true;
196
- let isFinish = isFinished();
197
- if (isFinish) {
198
- let datas = statusArr.map((item) => item.data);
199
- _finally(datas);
200
- }
201
- };
202
- };
203
- // @ts-ignore
204
- while ((fn = arr.shift())) {
205
- fn(resolve(index)); // 给 resolve 函数追加参数,可以使用 bind 函数实现,这里使用了柯里化
206
- index++;
207
- }
208
- }
209
- /**
210
- * 函数节流
211
- *
212
- * @author https://www.cnblogs.com/moqiutao/p/6875955.html
213
- * @param fn
214
- * @param delay
215
- * @param mustRunDelay
216
- */
217
- function throttle(fn, delay, mustRunDelay) {
218
- var timer, t_start;
219
- return function () {
220
- var t_curr = +new Date();
221
- window.clearTimeout(timer);
222
- if (!t_start)
223
- t_start = t_curr;
224
- if (t_curr - t_start >= mustRunDelay) {
225
- // @ts-ignore
226
- fn.apply(this, arguments);
227
- t_start = t_curr;
228
- }
229
- else {
230
- var args = arguments;
231
- // @ts-ignore
232
- timer = window.setTimeout(() => fn.apply(this, args), delay);
233
- }
234
- };
216
+ function dateFormat(date, format) {
217
+ return formatDate.call(new Date(date), format);
235
218
  }
236
- /**
237
- * 复制文字到剪切板
238
- *
239
- * @param {string} text
240
- */
241
- function copyToClipboard(text) {
242
- if (navigator.clipboard)
243
- navigator.clipboard.writeText(text); // clipboard api 复制
244
- else {
245
- let textarea = document.createElement('textarea');
246
- document.body.appendChild(textarea); // 隐藏此输入框
247
- textarea.style.position = 'fixed';
248
- textarea.style.clip = 'rect(0 0 0 0)';
249
- textarea.style.top = '10px';
250
- textarea.value = text; // 赋值
251
- textarea.select(); // 选中
252
- document.execCommand('copy', true); // 复制
253
- document.body.removeChild(textarea); // 移除输入框
254
- }
219
+ function now(format = 'yyyy-MM-dd hh:mm') {
220
+ return formatDate.call(new Date(), format);
255
221
  }
256
222
 
257
- var utils = /*#__PURE__*/Object.freeze({
223
+ var date_format = /*#__PURE__*/Object.freeze({
258
224
  __proto__: null,
259
- copyToClipboard: copyToClipboard,
260
225
  dateFormat: dateFormat,
261
- dateFormat2: dateFormat2,
262
- isDebug: isDebug,
263
- isDev: isDev,
264
- parallel: parallel,
265
- throttle: throttle
226
+ now: now
266
227
  });
267
228
 
268
- /**
269
- * 默认的请求配置
270
- */
271
- const DEFAULT_XHR_CFG = {
272
- timeout: 5000,
273
- withCredentials: false,
274
- parseContentType: 'json'
275
- };
276
- /**
277
- * 全局请求的 head 参数
278
- */
279
- let BASE_HEAD_PARAMS = null;
280
- /**
281
- * 设置全局请求的 head 参数
282
- *
283
- * @param param
284
- */
285
- function setBaseHeadParams(params) {
286
- if (BASE_HEAD_PARAMS === null)
287
- BASE_HEAD_PARAMS = {};
288
- Object.assign(BASE_HEAD_PARAMS, params);
289
- }
290
- /**
291
- *
292
- * @param getOrDel
293
- * @param url
294
- * @param cb
295
- * @param params
296
- * @param cfg
297
- */
298
- function getOrDel(getOrDel, url, cb, params, cfg = DEFAULT_XHR_CFG) {
299
- let xhr = initXhr(cfg);
300
- if (params != null) {
301
- if (url.indexOf('?') != -1)
302
- url += '&' + toParams(params);
303
- else
304
- url += '?' + toParams(params);
229
+ function request(api, method, bodyData, callback, header) {
230
+ let headers = {};
231
+ if (header)
232
+ for (const key in header)
233
+ headers[key] = header[key];
234
+ method = method.toUpperCase();
235
+ let body = bodyData;
236
+ if (bodyData && (method === 'POST' || method === 'PUT')) {
237
+ if (headers['Content-Type'] == 'application/json')
238
+ body = JSON.stringify(bodyData);
239
+ else if (headers['Content-Type'] == "application/x-www-form-urlencoded")
240
+ body = json2formParams(bodyData);
305
241
  }
306
- xhr.open(getOrDel.toUpperCase(), url, true);
307
- xhr.onreadystatechange = function () {
308
- responseHandle(this, cb, cfg);
309
- };
310
- if (BASE_HEAD_PARAMS) // 设置自定义请求头
311
- for (let key in BASE_HEAD_PARAMS)
312
- xhr.setRequestHeader(key, BASE_HEAD_PARAMS[key]);
313
- xhr.send();
314
- }
315
- /**
316
- *
317
- * @param method
318
- * @param url
319
- * @param cb
320
- * @param params
321
- * @param cfg
322
- */
323
- function postOrPut(method, url, cb, params, cfg = DEFAULT_XHR_CFG) {
324
- let xhr = initXhr(cfg);
325
- xhr.open(method, url, true);
326
- xhr.onreadystatechange = function () {
327
- responseHandle(this, cb, cfg);
328
- };
329
- if (BASE_HEAD_PARAMS) // 设置自定义请求头
330
- for (let key in BASE_HEAD_PARAMS)
331
- xhr.setRequestHeader(key, BASE_HEAD_PARAMS[key]);
332
- // 此方法必须在 open() 方法和 send() 之间调用
333
- if (!cfg.contentType) // 如未设置,默认为表单请求
334
- xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
335
- else
336
- xhr.setRequestHeader("Content-Type", cfg.contentType);
337
- let _params = typeof params != 'string' ? toParams(params) : params;
338
- if (_params)
339
- xhr.send(_params);
340
- else
341
- xhr.send();
342
- }
343
- /**
344
- *
345
- * @param url
346
- * @param cb
347
- * @param params
348
- * @param cfg
349
- */
350
- function xhr_post_upload(url, cb, params, cfg = DEFAULT_XHR_CFG) {
351
- let xhr = initXhr(cfg);
352
- xhr.open('post', url, true);
353
- xhr.onreadystatechange = function () {
354
- responseHandle(this, cb, cfg);
355
- };
356
- if (BASE_HEAD_PARAMS) // 设置自定义请求头
357
- for (let key in BASE_HEAD_PARAMS)
358
- xhr.setRequestHeader(key, BASE_HEAD_PARAMS[key]);
359
- // 什么 Content-Type 都不设置
360
- xhr.send(params);
361
- }
362
- /**
363
- * XHR GET 请求
364
- *
365
- * @param url 请求地址
366
- * @param cb 回调函数 @example (json: {}, text: string) => void;
367
- * @param params 参数,必填,如无填空字符串 "";参数类型是json;参数值会进行 URL 编码,最后附加到 QueryString 中
368
- * @param cfg 配置,可选的
369
- */
370
- function xhr_get(url, cb, params, cfg = DEFAULT_XHR_CFG) {
371
- getOrDel('get', url, cb, params, cfg);
372
- }
373
- /**
374
- * XHR DELETE 请求
375
- *
376
- * @param url 请求地址
377
- * @param cb 回调函数 @example (json: {}, text: string) => void;
378
- * @param params 参数,必填,如无填空字符串 "";参数类型是json;参数值会进行 URL 编码,最后附加到 QueryString 中
379
- * @param cfg 配置,可选的
380
- */
381
- function xhr_del(url, cb, params, cfg = DEFAULT_XHR_CFG) {
382
- getOrDel('delete', url, cb, params, cfg);
383
- }
384
- /**
385
- * XHR POST 请求
386
- *
387
- * @param url 请求地址
388
- * @param cb 回调函数 @example (json: {}, text: string) => void;
389
- * @param params 参数,必填,如无填空字符串 "";参数类型可以是字符串或 json;参数值会进行 URL 编码
390
- * @param cfg 配置,可选的
391
- */
392
- function xhr_post(url, cb, params, cfg = DEFAULT_XHR_CFG) {
393
- postOrPut('post', url, cb, params, cfg);
394
- }
395
- /**
396
- * XHR PUT 请求
397
- *
398
- * @param url 请求地址
399
- * @param cb 回调函数 @example (json: {}, text: string) => void;
400
- * @param params 参数,必填,如无填空字符串 "";参数类型可以是字符串或 json;参数值会进行 URL 编码
401
- * @param cfg 配置,可选的
402
- */
403
- function xhr_put(url, cb, params, cfg = DEFAULT_XHR_CFG) {
404
- postOrPut('put', url, cb, params, cfg);
242
+ fetch(api, {
243
+ method,
244
+ headers: headers,
245
+ body,
246
+ credentials: 'include'
247
+ }).then(response => {
248
+ if (response.status === 404)
249
+ throw new Error('Not found 404: ' + api);
250
+ else if (response.status === 500)
251
+ throw new Error('Server error: ' + api);
252
+ else if (!response.ok)
253
+ throw new Error(`Unexpected status: ${response.status}`);
254
+ return response.json();
255
+ })
256
+ .then(data => {
257
+ if (callback)
258
+ callback(data); // 调用回调
259
+ })
260
+ .catch(error => {
261
+ console.error('Network error when fetching from: ' + api, error); // 网络错误时才会 reject Promise
262
+ });
405
263
  }
406
- /**
407
- * 初始化 XHR
408
- *
409
- * @param cfg
410
- * @returns
411
- */
412
- function initXhr(cfg) {
413
- let xhr = new XMLHttpRequest();
414
- if (cfg && cfg.timeout) {
415
- xhr.timeout = cfg.timeout;
416
- xhr.ontimeout = (e) => console.error('系统异常,XHR 连接服务超时');
264
+ function json2formParams(params) {
265
+ const pairs = [];
266
+ for (const [key, value] of Object.entries(params)) {
267
+ if (value !== null && value !== undefined && typeof value !== 'function')
268
+ pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
417
269
  }
418
- if (cfg && cfg.withCredentials)
419
- xhr.withCredentials = true;
420
- return xhr;
270
+ return pairs.join('&');
421
271
  }
422
272
  /**
423
- * 错误处理
273
+ * HTTP GET 请求
424
274
  *
425
- * @param xhr
275
+ * @param api API 地址
276
+ * @param callback
277
+ * @param header
426
278
  */
427
- function errHandle(xhr) {
428
- let msg;
429
- if (xhr.status <= 400)
430
- msg = '请求参数错误或者权限不足。';
431
- else if (xhr.status <= 500)
432
- msg = '服务端异常。';
433
- else
434
- msg = `未知异常,HTTP code:${xhr.status}。`;
435
- if (!xhr.responseText)
436
- msg += " 服务端返回空的字符串!";
437
- console.error(msg, xhr.responseText);
279
+ function get(api, callback, header) {
280
+ request(api, 'GET', null, callback, header);
438
281
  }
439
- /**
440
- * 响应处理
441
- *
442
- * @param xhr
443
- * @param cb
444
- * @param cfg
445
- */
446
- function responseHandle(xhr, cb, cfg) {
447
- if (xhr.readyState == 4) {
448
- if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
449
- let text = xhr.responseText;
450
- let json;
451
- if (!text)
452
- console.warn('服务端没有返回任何字符串');
453
- switch (cfg.parseContentType) {
454
- case 'text':
455
- break;
456
- case 'xml':
457
- json = xhr.responseXML;
458
- break;
459
- case 'json':
460
- default:
461
- try {
462
- json = JSON.parse(text);
463
- }
464
- catch (e) {
465
- console.error('解析 JSON 时候发生错误,非法 JSON');
466
- console.warn(e);
467
- }
468
- }
469
- cb && cb(json, text);
470
- }
471
- else
472
- errHandle(xhr);
473
- }
282
+ function post(api, bodyData, callback, header) {
283
+ request(api, 'POST', bodyData, callback, Object.assign({ 'Content-Type': 'application/json' }, header));
474
284
  }
475
- /**
476
- * 对象转换为 URL 参数列表,用 & 分隔
477
- *
478
- * @param {Object} param JSON 对象
479
- * @returns URL 参数列表
480
- */
481
- function toParams(param) {
482
- let result = "";
483
- for (let name in param) {
484
- if (typeof param[name] != "function")
485
- result += "&" + name + "=" + encodeURIComponent(param[name]);
486
- }
487
- return result.substring(1);
285
+ function postForm(api, bodyData, callback, header) {
286
+ request(api, 'POST', bodyData, callback, Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded' }, header));
488
287
  }
489
- /**
490
- * 获取 QueryString 的某个参数
491
- *
492
- * @param val
493
- * @returns
494
- */
495
- function getQuery(val) {
496
- const w = location.hash.indexOf('?');
497
- const query = location.hash.substring(w + 1);
498
- let vars = query.split('&');
499
- for (let i = 0; i < vars.length; i++) {
500
- const pair = vars[i].split('=');
501
- if (pair[0] == val)
502
- return pair[1];
503
- }
504
- return '';
288
+ function put(api, bodyData, callback, header) {
289
+ request(api, 'PUT', bodyData, callback, Object.assign({ 'Content-Type': 'application/json' }, header));
505
290
  }
506
- function getPageList(self, listArray, callback) {
507
- return (j) => {
508
- if (j.status) {
509
- listArray.total = j.total;
510
- listArray.data = j.data;
511
- callback && callback();
512
- }
513
- else
514
- self.$Message.warning(j.message || '获取数据失败');
515
- };
291
+ function putForm(api, bodyData, callback, header) {
292
+ request(api, 'PUT', bodyData, callback, Object.assign({ 'Content-Type': 'application/x-www-form-urlencoded' }, header));
293
+ }
294
+ function del(api, callback, header) {
295
+ request(api, 'DELETE', null, callback, header);
516
296
  }
517
297
 
518
- var xhr = /*#__PURE__*/Object.freeze({
298
+ var xhr_fetch = /*#__PURE__*/Object.freeze({
519
299
  __proto__: null,
520
- getPageList: getPageList,
521
- getQuery: getQuery,
522
- setBaseHeadParams: setBaseHeadParams,
523
- toParams: toParams,
524
- xhr_del: xhr_del,
525
- xhr_get: xhr_get,
526
- xhr_post: xhr_post,
527
- xhr_post_upload: xhr_post_upload,
528
- xhr_put: xhr_put
300
+ del: del,
301
+ get: get,
302
+ post: post,
303
+ postForm: postForm,
304
+ put: put,
305
+ putForm: putForm
529
306
  });
530
307
 
531
- exports.Cookies = cookies;
532
- exports.Dom = dom;
308
+ exports.DateFormat = date_format;
533
309
  exports.Utils = utils;
534
- exports.Xhr = xhr;
310
+ exports.Xhr = xhr_fetch;
311
+ exports.XhrFetch = xhr_fetch;
535
312
 
536
313
  }));
314
+ //# sourceMappingURL=index.umd.js.map