123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639 |
- import $ from 'jquery';
- import WjySdk from 'extSdk';
- import {Indicator, Toast, MessageBox} from 'mint-ui';
- const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1; //android终端
- const isiOS = navigator.userAgent.match(/(iPhone|iPod|iPad);?/i); //ios终端
- var lib = {};
- var BDY = {};
- BDY.params = [];
- BDY.timeout = [];
- BDY.interval = [];
- BDY.xhrs = [];
- BDY.xhrCount = 0;
- BDY.appId = 4;
- //+++++++++++++++++++++++++++ hash 参数控制 +++++++++++++++++++++++++++++++++++++
- /**
- * js获取url参数的值,(函数内部decodeURIComponent值)
- * @author benzhan
- * @param {string} name 参数名
- * @return {string} 参数值
- */
- function getParam(name) {
- //先获取#后面的参数
- var str = document.location.hash.substr(2);
- var value = getParam2(name, str);
- if (value == null) {
- str = document.location.search.substr(1);
- value = getParam2(name, str);
- }
- return value;
- };
- function getParam2(name, str) {
- //获取参数name的值
- var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
- //再获取?后面的参数
- var r = str.match(reg);
- if (r != null) {
- try {
- return decodeURIComponent(r[2]);
- } catch (e) {
- return null;
- }
- }
- return null;
- };
- /**
- * js设置url中hash参数的值, (函数内部encodeURIComponent传入的value参数)
- * @author benzhan
- * @param {string} name 参数名
- * @return {string} value 参数值
- */
- function setParam(name, value, causeHistory) {
- var search = document.location.search.substr(1);
- if ($.type(name) === "object") {
- // 支持 setParam(value, causeHistory)的写法
- causeHistory = value;
- value = name;
-
- for (var key in value) {
- search = setParam2(key, value[key], search);
- }
- } else {
- search = setParam2(name, value, search);
- }
- if (causeHistory) {
- if (history.pushState) {
- history.pushState({}, null, "?" + search);
- } else {
- document.location.search = search;
- }
- } else {
- if (history.replaceState) {
- history.replaceState({}, null, "?" + search);
- } else {
- console.error("history.replaceState:" + history.replaceState);
- }
- }
- };
- function setParam2(name, value, str) {
- if ($.type(name) === "object") {
- // 支持 setParam(value, causeHistory)的写法
- str = value;
- value = name;
- for (var key in value) {
- str = setParam2(key, value[key], str);
- }
- return str;
- } else {
- var prefix = str ? "&" : "";
- var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
- var r = str.match(reg);
- value = encodeURIComponent(value);
- if (r) {
- if (r[2]) {
- var newValue = r[0].replace(r[2], value);
- str = str.replace(r[0], newValue);
- } else {
- var newValue = prefix + name + "=" + value + "&";
- str = str.replace(r[0], newValue);
- }
- } else {
- var newValue = prefix + name + "=" + value;
- str += newValue;
- }
-
- return str;
- }
- };
- function removeParam(name, causeHistory) {
- var search = document.location.search.substr(1);
- var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
- r = search.match(reg);
- if (r) {
- if (r[1] && r[3]) {
- search = search.replace(r[0], '&');
- } else {
- search = search.replace(r[0], '');
- }
- }
-
- if (causeHistory) {
- document.location.search = search;
- } else {
- if (history.replaceState) {
- history.replaceState({}, null, "?" + search);
- } else {
- console.error("history.replaceState:" + history.replaceState);
- }
- }
- };
- function parseHash(strUrl) {
- strUrl = strUrl ? strUrl : document.location.search.substr(1);
-
- //获取参数name的值
- var reg = new RegExp("(^|!|#|&|\\?)(\\w*)=([^&]*)", "g");
-
- //先获取#后面的参数
- var r = reg.exec(strUrl);
- var datas = {};
-
- var i = 0;
- while (r != null) {
- datas[r[2]] = decodeURIComponent(r[3]);
- r = reg.exec(strUrl);
- }
-
- return datas;
- };
- // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- // +++++++++++++++++++++++++++ get 和 post +++++++++++++++++++++++++++++++++++++
- function _getDefaultData(data) {
- data = data || {};
- var ouid = getCookie('ouid');
- ouid && (data.ouid = ouid);
-
- var defaultKeys = ['gym_id'];
- for (var i in defaultKeys) {
- var key = defaultKeys[i];
- var value = getLocalData(key);
- if (value && value != "undefined") {
- data[key] = value;
- }
- }
-
- for (var k in data) {
- var v = data[k];
- if (v == null || typeof v === 'undefined') {
- delete data[k];
- } else {
- if (typeof v === 'string') {
- data[k] = $.trim(v);
- }
- }
- }
-
- return data;
- }
- /**
- * option object {'cache', 'loading', 'onTimeout'}
- * cache为every、once
- */
- function post(url, data, callback, option) {
- option = option || {};
- // 支持postCross(url, callback)的写法;
- if ( typeof data == 'function') {
- option = callback || {};
- callback = data;
- data = {};
- }
- data = _getDefaultData(data);
- var xhr = new XMLHttpRequest();
- BDY.xhrs.push(xhr);
- BDY.xhrCount++;
- xhr.index = BDY.xhrs.length;
- xhr.open("POST", url);
- xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xhr.withCredentials = true;
- // 兼容ios6.0会缓存
- if (window.KalaGame) {
- xhr.setRequestHeader("Cache-Control", "no-cache");
- }
- data = $.param(data);
- //获取cache的key
- if (option['cache']) {
- var cacheKey = 'ajaxCache-' + url + '?' + data;
- //如果有cache则不出现loading
- var isCached = _loadAjaxCache(cacheKey, callback);
- if (isCached) {
- option['loading'] = false;
- if (option['cache'] == "must") {
- return;
- }
- }
- }
- if (option['loading']) {
- xhr.timeout = 15000;
- showLoading();
- }
- xhr.send(data);
- xhr.ontimeout = option['onTimeout'] || function () {
- callback && callback({result:0, code:-11, msg:"网络超时,请重试"});
- };
- // 响应处理
- xhr.onload = function() {
- BDY.xhrs[xhr.index] = null;
- BDY.xhrCount--;
- option['loading'] && hideLoading();
- var objResult = _getAjaxResult(xhr.responseText);
- if (objResult['result'] && option['cache']) {
- var cache = localStorage.getItem(cacheKey);
- if (cache && cache == xhr.responseText) {
- // 网络返回跟缓存一致
- return;
- } else {
- localStorage.setItem(cacheKey, xhr.responseText);
- }
- }
-
- callback && callback(objResult);
- };
-
- }
- function get(url, callback, option) {
- option = option || {};
- var xhr = new XMLHttpRequest();
- BDY.xhrs.push(xhr);
- BDY.xhrCount++;
- var data = {};
- _getDefaultData(data);
- for (var key in data) {
- if (!getParam2(key, url)) {
- url += url.indexOf('?') >= 0 ? '&' : '?';
- url += key + '=' + data[key];
- }
- }
- xhr.url = url;
- option['loading'] && showLoading();
- xhr.onreadystatechange = function() {
- if (xhr.readyState != 4) {
- return;
- }
- BDY.xhrs[xhr.index] = null;
- BDY.xhrCount--;
- if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && location.protocol == 'file:')) {
- option['loading'] && hideLoading();
- if (option['type'] == 'text') {
- callback(xhr.responseText);
- } else {
- callback(_getAjaxResult(xhr.responseText));
- }
- }
- };
- xhr.open("GET", url);
- // xhr.withCredentials = true;
- xhr.send();
- }
- function _getAjaxResult(text) {
- var objResult = {};
- var objError = {
- result : 0,
- msg : "系统繁忙,请稍后再试!"
- };
- try {
- objResult = JSON.parse(text);
- if (typeof objResult !== 'object' || objResult === null) {
- objResult = objError;
- }
- } catch (ex) {
- //非json的处理
- objResult = objError;
- }
- return objResult;
- }
- function _loadAjaxCache(cacheKey, callback) {
- var cache = localStorage.getItem(cacheKey);
- if (cache) {
- var objResult = JSON.parse(cache);
- objResult._fromCache = true;
- callback && callback(objResult);
-
- return true;
- } else {
- return false;
- }
- }
- function _handleResult(callback, objResult) {
- //session_id失效,重新验证登录
- if(!objResult.result && objResult.code == -5) {
- openLogin();
- } else {
- callback && callback(objResult);
- }
- }
- function _deserialize(value){
- if (typeof value != 'string') {
- return undefined
- }
- try {
- return JSON.parse(value)
- }catch(e) {
- return value || undefined
- }
- }
- function getLocalData(key) {
- return getParam(key) || _deserialize(localStorage.getItem(key));
- }
- function setLocalData(key, val) {
- localStorage.setItem(key, JSON.stringify(val))
- }
- function getCookie(name) {
- var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
- if(arr=document.cookie.match(reg))
- return unescape(arr[2]);
- else
- return null;
- }
- function _setTimeout(callback, timeout) {
- var timer = setTimeout(callback, timeout);
- BDY.timeout.push(timer);
- return timer;
- }
- function _setInterval(callback, timeout) {
- var timer = setInterval(callback, timeout);
- BDY.interval.push(timer);
- return timer;
- }
- function _clearRes() {
- var len;
- var timeout = BDY.timeout;
- var interval = BDY.interval;
- len = timeout.length;
- for (var i = 0; i < len; i++) {
- clearTimeout(timeout[i]);
- }
- len = interval.length;
- for (var i = 0; i < len; i++) {
- clearInterval(interval[i]);
- }
- // 重置timer
- BDY.timeout = [];
- BDY.interval = [];
- for (var i in BDY.xhrs) {
- BDY.xhrs[i] && BDY.xhrs[i].abort();
- }
- BDY.xhrs = [];
- BDY.xhrCount = 0;
- }
- // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- var loadingDelayHandler = 0;
- var loadingTimeoutHandler = 0;
- var loadDialog;
- function showLoading(text, timeout, cancelable, delay) {
- // 超时时间为15s
- timeout = timeout || 15000;
- // 0.2s后才显示loading
- delay = delay || 200;
-
- if (cancelable == null) {
- cancelable = true;
- } else {
- cancelable = !!cancelable;
- }
-
- if (loadingDelayHandler) {
- return;
- }
-
- loadingDelayHandler = setTimeout(function() {
- if (!WjySdk.showLoading(text, timeout, cancelable)) {
- Indicator.open(text);
-
- loadingTimeoutHandler = setTimeout(function(){
- hideLoading();
- showTip("加载超时,请稍后再试");
- }, timeout);
- }
- }, delay);
- }
- function hideLoading() {
- loadingDelayHandler && clearTimeout(loadingDelayHandler);
- loadingDelayHandler = 0;
- loadingTimeoutHandler && clearTimeout(loadingTimeoutHandler);
- loadingTimeoutHandler = 0;
- try {
- Indicator.close();
- } catch(e) {}
- }
- function showErrorTip(msg, timeout) {
- if (!msg) { return; }
- timeout = timeout || 3000;
- if (!WjySdk.showErrorTip(msg, timeout)) {
- Toast({
- message : msg,
- position: 'middle',
- duration: timeout
- });
- }
- }
- function showTip(msg, timeout) {
- if (!msg) { return; }
- timeout = timeout || 2000;
- if (!WjySdk.showTip(msg, timeout)) {
- Toast({
- message : msg,
- position: 'bottom',
- duration: timeout
- });
- }
- }
- function showDialog(msg, callback, title, buttonLabels) {
- title = title || "提示";
- buttonLabels = buttonLabels || "确定";
- MessageBox({
- title: title,
- message: msg,
- confirmButtonText: buttonLabels
- }).then(action => {
- callback && callback(action);
- });
- }
- function confirm(msg, callback, title, buttonLabels) {
- title = title || "提示";
- buttonLabels = buttonLabels || "确定,取消";
- if (!WjySdk.confirm(msg, callback, title, buttonLabels)) {
- MessageBox.confirm(msg, title).then(action => {
- callback && callback(true);
- }).catch(err => {
- callback && callback(false);
- });
- }
- }
- function handleTime(timeStamp,type){
- if(!timeStamp) return "--"
- var date = new Date(timeStamp)
- var year = date.getFullYear()
- var month = date.getMonth()+1
- var day = date.getDate()
- var hour = date.getHours()
- var minute = date.getMinutes()
- month = month >= 10 ? month : "0"+month
- day = day >= 10 ? day : "0"+day
- hour = hour >= 10 ? hour : "0"+hour
- minute = minute >= 10 ? minute : "0"+minute
- if(type==2) {
- return year+"-"+month+"-"+day+" "+hour+":"+minute
- } else {
- return year+"年"+month+"月"+day+"日 "+hour+":"+minute
- }
- }
- function checkWXAgent() {
- var ua = navigator.userAgent.toLowerCase();
- if (ua.match(/micromessenger/i) == "micromessenger") {
- return true;
- } else {
- return false;
- }
- }
- function getDomain(){
- var host = location.host;
- if (host.indexOf("127.0.0.1") > -1 || host.indexOf("test-minipay.ouj.com") > -1) {
- lib.apiUrl = "//test-api-minipay.ouj.com";
- lib.domain = "//test-minipay.ouj.com";
- } else {
- lib.apiUrl = "//api-minipay.ouj.com";
- lib.domain = "//minipay.ouj.com";
- }
- }
- //设置微信分享的参数
- function setWxShare(data,sCallback,cCallBack){ //分享数据,success回调,cancel回调
- if (!checkWXAgent()) return;
- var checkWxInterval = setInterval(function(){
- if(wx) {
- clearInterval(checkWxInterval);
- // 适配https
- if(!data.imgUrl.match(/http\:\/\/|https\:\/\//)) {
- data.imgUrl = "https:" + data.imgUrl
- }
-
- wx.ready(function(){
- wx.onMenuShareTimeline({
- title: data.title, // 分享标题
- link: data.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
- imgUrl: data.imgUrl, // 分享图标
- success: function () {
- sCallback && sCallback(); // 用户确认分享后执行的回调函数
- },
- cancel: function () {
- cCallBack && cCallBack(); // 用户取消分享后执行的回调函数
- }
- });
- wx.onMenuShareAppMessage({
- title: data.title, // 分享标题
- desc: data.desc, // 分享描述
- link: data.link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
- imgUrl: data.imgUrl, // 分享图标
- success: function () {
- sCallback && sCallback(); // 用户确认分享后执行的回调函数
- },
- cancel: function () {
- cCallBack && cCallBack(); // 用户取消分享后执行的回调函数
- }
- });
- });
- }
- },200);
- }
- function formatHttpProtocol(object) {
- let fData = JSON.stringify(object);
- fData = fData.replace(/http\:\/\//g, "//");
- return JSON.parse(fData);
- }
- function init(){
- getDomain();
- }
- init();
- lib.getParam = getParam;
- lib.getParam2 = getParam2;
- lib.setParam = setParam;
- lib.setParam2 = setParam2;
- lib.removeParam = removeParam;
- lib.parseHash = parseHash;
- lib.post = post;
- lib.get = get;
- lib.getLocalData = getLocalData;
- lib.setLocalData = setLocalData;
- lib.getCookie = getCookie;
- lib.setTimeout = _setTimeout;
- lib.setInterval = _setInterval;
- lib.clearRes = _clearRes;
- lib.showLoading = showLoading;
- lib.hideLoading = hideLoading;
- lib.showErrorTip = showErrorTip;
- lib.showTip = showTip;
- lib.showDialog = showDialog;
- lib.confirm = confirm;
- lib.checkWXAgent = checkWXAgent;
- lib.handleTime = handleTime;
- lib.setWxShare = setWxShare;
- lib.formatHttpProtocol = formatHttpProtocol;
- lib.appid = {
- taptapStar: 1010
- }
- export default lib;
|