一个完整的前端项目往往会进行一些必要的抽取公用代码进行封装,这里记录js常用工具及统一的公共请求的封装。
一 2017年 第一版web管理后台在用
web后台管理页面用
/**
* Created by hua on 2017/8/24.
*/
var requestResult={
success :0,
failure:1,
failureMsg:2
}
jx={
reqAjax:function (isSync,url,fnSuccess,fnFailure) {
$.ajax({
type: "post",
dataType:"json",
async: isSync||true,
url: url,
success: function (data) {
console.log(data);
if (data.code ==requestResult.success ){
if ( jQuery.isFunction( fnSuccess ) ) {
fnSuccess.call();
}else{
alert("操作成功。");
}
}else{
if (data.code ==requestResult.failure){
alert("操作失败!");
}
if (data.code ==requestResult.failureMsg){
if (data.errMsg!=''){
alert(data.errMsg);
}else{
alert("操作失败,返回信息异常!")
}
}
if ( jQuery.isFunction( fnFailure ) ) {
fnFailure.call();
}
}
},
error:function(err){
alert("系统请求错误,请联系管理员!");
}
});
},
req:function (url,fnSuccess) {
jx.reqAjax(false,url, fnSuccess,null);
},
createNativeRequest: function createRequest()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("您的浏览器不支持登陆!");
return false;
}
}
}
return xmlHttp;
}
,nativeReq:function (async,url,param,fuSccess,fuFail) {
console.log('using native ajax.');
var xmlhttp= jx.createNativeRequest();
console.log('create native xmlhttp');
console.log(xmlhttp);
xmlhttp.open("POST",url,async||false);// 为空时同步
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
if (!async){
xmlhttp.send(param);
var result= xmlhttp.responseText;
console.log(result);
return result;
}else{
xmlhttp.onreadystatechange=function state_Change() {
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200) {
if (fuSccess && typeof(fuSccess) == "function") {
fuSccess();
}
}else
{
if (fuFail && typeof(fuFail) == "function") {
fuFail();
}
}
}
};
xmlhttp.send(param);
}
}
};
jxCookie={
setCookie:function (name,value)
{ var Days = 7;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
},
getCookie:function (name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
},
delCookie:function (name)
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
}
/**按钮等待进度 使用方法: jxProcess.run(butid, txtid, 1,30,'已发送成功(_sec_)') 说明:butid 和 txtid 为Input元素对象ID,1 代表每隔几秒刷新次数, 30代表等待30秒,最后的参数为等时间显示到按钮的字体动态显示参数 _sec_ **/
var jxProcess={
cur:60,
jqElemBut:undefined,
jqElemTxt:undefined,
normalButLabel:undefined,
dyTimeLabel:undefined,
t:undefined,
startWait:function () {
if (jxProcess.cur > 0){
var label= jxProcess.dyTimeLabel.replace("_sec_",jxProcess.cur);
jxProcess.cur--;
jxProcess.jqElemBut.html(label);
}else{
jxProcess.runStop();
}
},
getJqueryObjById:function(id){
var _id="#"+id;
return $(_id);
},
run:function (butId,txtId,timeSec,sumSec,dyTimeLabel) {
var $elemBut= jxProcess.getJqueryObjById(butId);
var $elemTxt=jxProcess.getJqueryObjById(txtId);
$elemBut.attr("disabled",true);
$elemTxt.attr("readonly",true);
jxProcess.cur = sumSec||60;
jxProcess.jqElemBut=$elemBut;
jxProcess.jqElemTxt=$elemTxt;
jxProcess.normalButLabel=$elemBut.html();
jxProcess.dyTimeLabel=dyTimeLabel||'请耐心等待_sec_秒.'
jxProcess.t = window.setInterval('jxProcess.startWait()',timeSec*1000||1000);
},
runStop:function () {
if (jxProcess.t!=undefined){
jxProcess.jqElemBut.attr("disabled",false);
if (jxProcess.jqElemTxt){
jxProcess.jqElemTxt.attr("readonly",false);
}
jxProcess.jqElemBut.html(jxProcess.normalButLabel);
window.clearInterval(jxProcess.t);
console.log("clearInterval");
jxProcess.t=undefined;
}
}
}
二 2018年,在微信小程序在使用,项目要求加密请求要用rc4算法加密。
//引用配置文件
const cfg = require('../config.js');
//打印调试信息
function tag(obj,msg) {
console.log(new Date());
console.log("==========begin("+msg+")===========")
try {
console.log(obj);
} catch (e) {
console.log('print err !!!');
}
console.log("==========end("+msg+")===========")
}
//封包
function getPackage(data){
var data_str='';
if(data){
data_str=JSON.stringify(data);
}
var pack={
appKey:'123456',
version:'1.0.0',
isEncrypt:'N',
data:data_str
}
return pack;
}
//取得用户openid
function getOpenid(){
var openid = getCache("openid");
if (openid) {
return openid;
}
wx.login({
//获取code
success: function (res) {
var code = res.code //返回code
var url = cfg.config.getOpenIdUrl+'&js_code=' + code + '&grant_type=authorization_code';
tag(url,"get openid url");
wx.request({
url: url,
data: {},
header: {
'content-type': 'application/json'
},
success: function (res) {
if (res.data.openid){
setCache("openid", res.data.openid);
}
}
})
}
});
return openid;
}
function setCache(key, value) {
if (key != null && value != null) {
try {
wx.setStorageSync(key, value);
tag(value, "保存缓存成功 key=" + key);
return true;
} catch (e) {
tag(e, "保存到缓存失败 key=" + key + " value=" + value);
}
}
return false;
}
function getCache(key) {
var obj = null;
if (key) {
try {
obj = wx.getStorageSync(key);
tag(obj, "从缓存取 key=" + key);
} catch (e) {
tag(e, "从缓存取数据失败 key=" + key);
}
}
return obj;
}
function isMobile(mobile) {
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
return myreg.test(mobile);
}
//显示成功信息
function show(title,icon){
wx.showToast({
title: title||'JX信息提示',
icon:icon||'success',
duration: 1500
});
}
//显示错误信息
function showErr(title){
show(title,'loading');
}
function getLoginToken(){
return getCache('loginToken');
}
function setLoginToken(loginToken) {
return setCache('loginToken', loginToken);
}
//原始处理,不对外开发
function reqPackOrg(reqUrl, pack, fnSuccess, fnFail) {
wx.request({
method: 'POST',
url: reqUrl,
data: pack,
header: {
'content-type': 'application/x-www-form-urlencoded',
'Cookie': 'loginToken='+getLoginToken()
},
success: function (result) {
tag(result, "结果处理");
if (fnSuccess) {
fnSuccess.call(result);
} else {
show("操作成功");
}
},
fail: function (result) {
tag(res, "调用API submit fail");
if (fnFail) {
fnFail.call(result);
} else {
showErr("操作失败!");
}
},
complete: function (result) {
tag(result, "调用API结果submit complete");
}
});
}
//结合后台业务处理,统一调用
function reqPack(reqUrl, pack, fnSuccess, fnFail, fnComplete){
wx.request({
method: 'POST',
url: reqUrl,
data: pack,
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (result) {
var pack= result.data;
tag(pack, "结果处理");
if (pack.resultCode==200){
var busData = pack.data;
if (typeof busData== 'string') {
busData = busData.replace(/\ufeff/g, "");//重点
var jsonObj = JSON.parse(busData);
pack.data = jsonObj;
}
if (fnSuccess) {
if (fnSuccess.length == 1){
fnSuccess.call(this, pack);
}else{
fnSuccess.call();
}
} else {
show("操作成功");
}
}else{
if (fnFail) {
fnFail.call(result);
}else{
if (pack.resultCode && pack.resultMsg) {
showErr( pack.resultMsg + "[" + pack.resultCode + "]");
} else {
showErr("处理错误!");
}
}
}
},
fail: function (result) {
tag(res, "调用API submit fail");
if (fnFail) {
fnFail.call(result);
}else{
showErr("操作失败!");
}
},
complete: function (result) {
tag(result, "调用API结果submit complete");
if (fnComplete){
fnComplete.call();
}
}
});
}
function reqData(api, jsonData, fnSuccess, fnFail,fnComplete) {
var reqUrl=cfg.config.jx_url+api;
var pack = getPackage(jsonData);
reqPack(reqUrl, pack, fnSuccess, fnFail, fnComplete);
}
function req(api, fnSuccess, fnFail) {
var reqUrl = cfg.config.jx_url + api;
var pack = getPackage(null);
reqPack(reqUrl, pack, fnSuccess, fnFail,null)
}
let curUserInfo = 'curUserInfo';
function setUserInfoCache(userInfo) {
var memberInfo = {
nickName: userInfo.nickName,
org: userInfo
};
setCache(curUserInfo, memberInfo)
}
function getUserInfo(){
return getCache(curUserInfo);
}
//每个业务页面初始化处理
function init(){
var token=getLoginToken();
tag(token,"检测在线标识状态");
if(!token){
wx.redirectTo({
url: cfg.config.loginUrl
});
}
}
module.exports = {
getPackage: getPackage,
tag: tag,
getOpenid: getOpenid,
isMobile: isMobile,
reqData: reqData,
req:req,
setUserInfoCache: setUserInfoCache,
show: show,
showErr: showErr,
getLoginToken: getLoginToken,
setLoginToken: setLoginToken,
getUserInfo: getUserInfo,
init: init
}
三 2019年后,公司开始接很多的项目,小程序项目基本都用uni-app框架开发,再优化一点,根据使用情况对function request(method, reqUrl, pack, fnSuccess)去掉了失败函数传参。
"use strict";
//TestServer
//var baseUrl = 'http://192.168.22.193:8092'
//外网地址
var baseUrl = 'http://47.xx.xx.57:8063'
//线上
// var baseUrl = 'https://xcx.xxx.xxx'
//封包
function getPackage(data) {
let data_str = '';
if (data) {
data_str = JSON.stringify(data);
}
let pack = {
language:1,
isEncrypt: 'N',
data: data_str
}
return pack;
}
function request(method, reqUrl, pack, fnSuccess) {
pack = getPackage(pack);
uni.request({
method: method || 'POST',
url: baseUrl + reqUrl,
data: pack,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': getCache("token")? getCache("token") : ""
},
success: function(result) {
let pack = result;
if (fnSuccess) {
if (fnSuccess.length == 1) {
fnSuccess.call(this, pack);
} else if (fnSuccess.length == 2) {
fnSuccess.call(this, pack, pack.data.data);
} else {
fnSuccess.call();
}
}
else {
showToast("操作成功");
}
},
fail: function(result) {
try {
if (result.errMsg.indexOf('request:fail') != -1) {
alert("似乎已断开与互联网的连接");
} else {
alert("操作失败!");
}
} catch (e) {
alert("操作失败!");
}
}
})
}
function navigateTo(url) {
uni.navigateTo({
url: url
});
}
function switchTab(url) {
uni.switchTab({
url: url
});
}
function redirectTo(url) {
uni.redirectTo({
url: url
});
}
function showToast(title, icon) {
uni.showToast({
title: title || '出错了',
icon: icon || 'success',
duration: 2000
});
}
// alert
function alert(msg, title, success) {
uni.showModal({
title: '温馨提示' || title,
content: msg,
showCancel: false,
confirmColor: "#000",
success: success || {}
})
}
//设置缓存
function setCache(key, value) {
if (key != null && value != null) {
try {
uni.setStorageSync(key, value);
// console.log('设置缓存' + key + '=' + value);
} catch (e) {
console.log(e, "保存缓存失败")
}
}
}
//取出缓存
function getCache(key) {
var obj = null;
if (key) {
try {
obj = uni.getStorageSync(key);
// console.log("取出缓存", obj)
} catch (e) {
console.log(e, "取出缓存失败")
}
}
return obj;
}
//分享页面
function onShareAppMessage(title,url) {
return {
title: title || '',
path: 'pages/home/home'||url
}
}
// 手机验证
function isMobile(mobile) {
// 最新正则
var myreg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
return myreg.test(mobile);
}
// 身份证验证
function isId(isId) {
var myreg = /\d{17}[\d|x]|\d{15}/;
return myreg.test(isId);
}
// 邮箱验证
function iseMail(iseMail) {
var myreg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
return myreg.test(iseMail);
}
// QQ验证
function isQQ(isQQ) {
var myreg = /^[1-9]\d{4,9}$/;
return myreg.test(isQQ);
}
//补全时间两位数
function prefixZero(n, m) {
var _a = (Array(m).join(0) + n).slice(-m)
return _a
}
module.exports = {
request: request,
navigateTo: navigateTo,
switchTab: switchTab,
redirectTo:redirectTo,
showToast: showToast,
alert: alert,
setCache: setCache,
getCache: getCache,
onShareAppMessage:onShareAppMessage,
baseUrl:baseUrl,
isMobile:isMobile,
isId:isId,
iseMail:iseMail,
isQQ:isQQ,
prefixZero:prefixZero
}
这几年间公司加入专开发小程序的同事,这里太忙了我也没有时间怎么去关注了,后面发现他们具然所有的小程序项目都在用,而且连引用的文件名都没有改,如图:
四 2023年后小程序项目基本开始外包,查看了被外包修改后的代码,发现还是变化不大。
"use strict";
//TestServer
//var baseUrl = 'http://192.168.22.193:8888'
//外网地址
var baseUrl = 'https://xx.xx.xx.xx'
//线上
// var baseUrl = 'https://xx.xx.xx'
//封包
function getPackage(data) {
let data_str = '';
if (data) {
data_str = JSON.stringify(data);
}
let pack = {
language:1,
isEncrypt: 'N',
data: data_str
}
return pack;
}
//8d2df462-b665-4441-8ed5-f216c8babf53
function addImgFun(tempFilePaths,fun){
for(var i=0;i<tempFilePaths.length;i++){
uni.uploadFile({
url:baseUrl+'/api/v1/file/uploadImgs', //仅为示例,非真实的接口地址
filePath: tempFilePaths[i],
header:{
'Authorization': getCache("token")? getCache("token") : ""
},
name: 'files',
success: (uploadFileRes) => {
console.log(JSON.parse(uploadFileRes.data).data[0]);
fun(JSON.parse(uploadFileRes.data).data[0])
}
});
}
}
//xx测试账号
setCache("token",'9d307453-f0b1-4f7f-9a8c-41c1f803de73');
// setCache("token",'cccf7a52-855b-42d8-b5cf-d48eb7f678c2');
// setCache("token",'74bc8184-ac49-424f-9029-273cfcbfdd62');
// setCache("token",'fdd31cad-e9ce-4ad0-afc8-8c3ad42e0dc9');
function request(method, reqUrl, pack, fnSuccess,err) {
// setCache("token",'8d2df462-b665-4441-8ed5-f216c8babf53');
// console.log(baseUrl + reqUrl)
if(!pack.noShowLoading){
uni.showLoading({
title: '加载中'
});
delete pack.noShowLoading;
}
pack = getPackage(pack);
uni.request({
method: method || 'POST',
url: baseUrl + reqUrl,
data: pack,
header: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': getCache("token")? getCache("token") : ""
},
success: function(result) {
uni.hideLoading();
let pack = result;
console.log("pack+++++++++",JSON.stringify(pack))
if(pack.data.code==400){
showToast(pack.data.msg);
if(pack.data.failReason==1||pack.data.failReason==2||pack.data.failReason==3){
setCache("token","");
setTimeout(function(){
uni.navigateTo({
url:"/pages/home/home"
})
},2000)
}else if(pack.data.failReason==26){
setTimeout(function(){
uni.reLaunch({
url:"../charge/charge"
})
},2000)
}else if(pack.data.failReason==12){
setTimeout(function(){
uni.navigateTo({
url:"../order/order"
})
},2000)
}else if(pack.data.failReason==13){
setTimeout(function(){
uni.navigateBack({
delta:1
})
},2000)
}
if(err){
err(pack);
}
return false;
}else if (pack.data.code&&pack.data.code==200&&fnSuccess) {
if (fnSuccess.length == 1) {
fnSuccess.call(this, pack);
} else if (fnSuccess.length == 2) {
fnSuccess.call(this, pack, pack.data.data);
} else {
fnSuccess.call();
}
}else{
showToast(pack.data.msg);
}
// else {
// showToast("操作成功");
// }
},
fail: function(result) {
uni.hideLoading();
try {
if (result.errMsg.indexOf('request:fail') != -1) {
// alert("似乎已断开与互联网的连接");
} else {
// alert("操作失败!");
}
} catch (e) {
// alert("操作失败!");
}
}
})
}
function navigateTo(url) {
uni.navigateTo({
url: url
});
}
function switchTab(url) {
uni.switchTab({
url: url
});
}
function redirectTo(url) {
uni.redirectTo({
url: url
});
}
function showToast(title, icon) {
uni.showToast({
title: title || '出错了',
icon: icon || 'none',
mask:true,
duration: 2000
});
}
// alert
function alert(msg, title, success) {
uni.showModal({
title: '温馨提示' || title,
content: msg,
showCancel: false,
confirmColor: "#000",
success: success || {}
})
}
//设置缓存
function setCache(key, value) {
if (key != null && value != null) {
try {
uni.setStorageSync(key, value);
// console.log('设置缓存' + key + '=' + value);
} catch (e) {
console.log(e, "保存缓存失败")
}
}
}
//取出缓存
function getCache(key) {
var obj = null;
if (key) {
try {
obj = uni.getStorageSync(key);
// console.log("取出缓存", obj)
} catch (e) {
console.log(e, "取出缓存失败")
}
}
return obj;
}
//分享页面
function onShareAppMessage(title,url) {
return {
title: title || '',
path: 'pages/home/home'||url
}
}
// 手机验证
function isMobile(mobile) {
// 最新正则
var myreg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
return myreg.test(mobile);
}
// 身份证验证
function isId(isId) {
var myreg = /\d{17}[\d|x]|\d{15}/;
return myreg.test(isId);
}
// 邮箱验证
function iseMail(iseMail) {
var myreg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
return myreg.test(iseMail);
}
// QQ验证
function isQQ(isQQ) {
var myreg = /^[1-9]\d{4,9}$/;
return myreg.test(isQQ);
}
//补全时间两位数
function prefixZero(n, m) {
var _a = (Array(m).join(0) + n).slice(-m)
return _a
}
//补全时间两位数
function login(fun) {
if(getCache("token")){
if(fun){
fun();
}
}else{
setCache("token",'')
uni.login({
provider: 'weixin',
success: function(loginRes) {
var data = {
code: loginRes.code
}
request("POST", "/api/v1/common/wxLogin", data, (res) => {
// if (res.data.ret_code == 200) {
setCache("token", res.data.data.token)
setCache("memberId",res.data.data.user.id)
if(res.data.data.user.plateNo){
setCache("memberPlateNo",res.data.data.user.plateNo);
}
if(fun){
fun();
}
// } else {
// comm.showToast(res.data.ret_msg, "none")
// }
})
}
})
}
}
module.exports = {
request: request,
navigateTo: navigateTo,
switchTab: switchTab,
redirectTo:redirectTo,
showToast: showToast,
alert: alert,
setCache: setCache,
getCache: getCache,
onShareAppMessage:onShareAppMessage,
baseUrl:baseUrl,
isMobile:isMobile,
isId:isId,
iseMail:iseMail,
isQQ:isQQ,
prefixZero:prefixZero,
addImgFun:addImgFun,
login:login,
}
小程序引入调用部分
import comm from '../../static/data/commFunc.js'
//方法区
let that = this
uni.showLoading({
title:"加载中"
})
//参数
var data = {
current: that.current
}
//调用
comm.request("POST","/app/v200801/member/order/list",data,(res) => {
console.log("res",res)
that.data = res.data.data.records
that.list = that.list.concat(res.data.data.records)
that.total = res.data.data.total
uni.hideLoading()
})