封装$.ajax
前提:需引入jQuery和layui
封装后的特性:可异步,可同步,整合了layUI一些样式
(后续会推出layui封装版本,用于快速开发出后端管理系统,兼容移动/pc屏幕。思想是:除了少量js代码,基本上只需要写好HTML即可实现页面上的增删改查。个人感觉比vue项目简单很多,我不需要定义data,不需要写事件,只需要写好HTML,自定义好属性功能就完成 ,专用于全栈且不是前后端分离项目)
使用方式:
var p = my.reqApi({url: 'base/BASE_Types_GetData2',data: JSON.stringify({}),contentType: 'application/json;charset=utf-8', //设置请求头信息done: function (result) {console.log('请求地址是:sm/FaceCost_Groups_GetData' )}});// await Promise.all([p]); //开启同步console.log("执行完成")
封装ajax:
/*** 封装统一的请求方法* @param {Object} obj - 请求配置对象* @param {string} obj.url - 请求URL* @param {string} [obj.type='POST'] - 请求方法 (GET/POST等)* @param {Object} [obj.data] - 请求参数* @param {string} [obj.dataType='json'] - 响应数据类型* @param {boolean} [obj.async=true] - 是否异步请求* @param {boolean} [obj.cache=true] - 是否缓存* @param {string} [obj.contentType='application/x-www-form-urlencoded'] - 请求头Content-Type* @param {boolean} [obj.processData=true] - 是否处理数据* @param {boolean} [obj.notLoad=false] - 是否不显示加载动画* @param {boolean} [obj.notLayMsg=false] - 请求执行成功返回msg有值时是否弹出展示* @param {Function} [obj.done] - 成功回调* @param {Function} [obj.error] - 失败回调* @param {Function} [obj.beforeSend] - 请求前回调* @returns {Promise} 返回Promise对象*/reqApi: function(obj) {// 设置默认值const defaults = {processData: true,contentType: 'application/x-www-form-urlencoded',async: true,cache: true,dataType: 'json',type: 'POST',notLoad: false,notLayMsg:false};// 合并用户配置和默认配置const config = { ...defaults, ...obj };// 显示加载动画let loadingIndex;if (!config.notLoad) {loadingIndex = layer.load(2, { shade: false });}// 返回Promise以便支持async/awaitreturn new Promise((resolve, reject) => {$.ajax({url: config.url,type: config.type,dataType: config.dataType,data: config.data,async: config.async,cache: config.cache,contentType: config.contentType,processData: config.processData,beforeSend: function(jqXHR, settings) {if (typeof config.beforeSend === 'function') {config.beforeSend(jqXHR, settings);}},success: function(result) {// 统一处理成功响应handleResponse(result, resolve, reject, config);},complete: function() {if (loadingIndex) layer.close(loadingIndex);},error: function(error) {handleError(error, reject, config);}});});/*** 处理响应结果*/function handleResponse(result, resolve, reject, config) {// 特殊状态码处理if (result.code === -100) {location.href = "";return;}// 成功状态码范围if (result.code != 200 && result.msg){layer.msg(result.msg);}else if(result.msg && !config.notLayMsg){layer.msg(result.msg);}// 回调处理if (typeof config.done === 'function') {config.done(result);}// Promise 解析resolve(result);}/*** 处理错误*/function handleError(error, reject, config) {let errorData;try {errorData = JSON.parse(error.responseText);} catch (e) {errorData = error;}// 回调处理if (typeof config.error === 'function') {config.error(errorData);} else {layer.msg('网络请求出错');}// Promise 拒绝reject(errorData);}}