lib.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. import $ from 'jquery';
  2. import BDY from 'BDY';
  3. import HiydSdk from 'extSdk';
  4. import Indicator from 'mint-ui/lib/Indicator';
  5. import Toast from 'mint-ui/lib/Toast';
  6. import MessageBox from 'mint-ui/lib/Message-Box';
  7. import 'mint-ui/lib/indicator/style.css';
  8. import 'mint-ui/lib/toast/style.css';
  9. import 'mint-ui/lib/message-box/style.css';
  10. // require('../artDialog/artDialog');
  11. //+++++++++++++++++++++++++++ hash 参数控制 +++++++++++++++++++++++++++++++++++++
  12. /**
  13. * js获取url参数的值,(函数内部decodeURIComponent值)
  14. * @author benzhan
  15. * @param {string} name 参数名
  16. * @return {string} 参数值
  17. */
  18. function getParam(name) {
  19. //先获取#后面的参数
  20. var str = document.location.hash.substr(2);
  21. var value = getParam2(name, str);
  22. if (value == null) {
  23. str = document.location.search.substr(1);
  24. value = getParam2(name, str);
  25. }
  26. return value;
  27. };
  28. function getParam2(name, str) {
  29. //获取参数name的值
  30. var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
  31. //再获取?后面的参数
  32. var r = str.match(reg);
  33. if (r != null) {
  34. try {
  35. return decodeURIComponent(r[2]);
  36. } catch (e) {
  37. return null;
  38. }
  39. }
  40. return null;
  41. };
  42. /**
  43. * js设置url中hash参数的值, (函数内部encodeURIComponent传入的value参数)
  44. * @author benzhan
  45. * @param {string} name 参数名
  46. * @return {string} value 参数值
  47. */
  48. function setParam(name, value, causeHistory) {
  49. var search = document.location.search.substr(1);
  50. if ($.type(name) === "object") {
  51. // 支持 setParam(value, causeHistory)的写法
  52. causeHistory = value;
  53. value = name;
  54. for (var key in value) {
  55. search = setParam2(key, value[key], search);
  56. }
  57. } else {
  58. search = setParam2(name, value, search);
  59. }
  60. if (causeHistory) {
  61. if (history.pushState) {
  62. history.pushState({}, null, "?" + search);
  63. } else {
  64. document.location.search = search;
  65. }
  66. } else {
  67. if (history.replaceState) {
  68. history.replaceState({}, null, "?" + search);
  69. } else {
  70. console.error("history.replaceState:" + history.replaceState);
  71. }
  72. }
  73. };
  74. function setParam2(name, value, str) {
  75. if ($.type(name) === "object") {
  76. // 支持 setParam(value, causeHistory)的写法
  77. str = value;
  78. value = name;
  79. for (var key in value) {
  80. str = setParam2(key, value[key], str);
  81. }
  82. return str;
  83. } else {
  84. var prefix = str ? "&" : "";
  85. var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");
  86. var r = str.match(reg);
  87. value = encodeURIComponent(value);
  88. if (r) {
  89. if (r[2]) {
  90. var newValue = r[0].replace(r[2], value);
  91. str = str.replace(r[0], newValue);
  92. } else {
  93. var newValue = prefix + name + "=" + value + "&";
  94. str = str.replace(r[0], newValue);
  95. }
  96. } else {
  97. var newValue = prefix + name + "=" + value;
  98. str += newValue;
  99. }
  100. return str;
  101. }
  102. };
  103. function removeParam(name, causeHistory) {
  104. var search = document.location.search.substr(1);
  105. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  106. r = search.match(reg);
  107. if (r) {
  108. if (r[1] && r[3]) {
  109. search = search.replace(r[0], '&');
  110. } else {
  111. search = search.replace(r[0], '');
  112. }
  113. }
  114. if (causeHistory) {
  115. document.location.search = search;
  116. } else {
  117. if (history.replaceState) {
  118. history.replaceState({}, null, "?" + search);
  119. } else {
  120. console.error("history.replaceState:" + history.replaceState);
  121. }
  122. }
  123. };
  124. function parseHash(strUrl) {
  125. strUrl = strUrl ? strUrl : document.location.search.substr(1);
  126. //获取参数name的值
  127. var reg = new RegExp("(^|!|#|&|\\?)(\\w*)=([^&]*)", "g");
  128. //先获取#后面的参数
  129. var r = reg.exec(strUrl);
  130. var datas = {};
  131. var i = 0;
  132. while (r != null) {
  133. datas[r[2]] = decodeURIComponent(r[3]);
  134. r = reg.exec(strUrl);
  135. }
  136. return datas;
  137. };
  138. // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  139. // +++++++++++++++++++++++++++ get 和 post +++++++++++++++++++++++++++++++++++++
  140. function _getDefaultData(data) {
  141. data = data || {};
  142. var ouid = getCookie('ouid');
  143. ouid && (data.ouid = ouid);
  144. var defaultKeys = ['gym_id'];
  145. for (var i in defaultKeys) {
  146. var key = defaultKeys[i];
  147. var value = getLocalData(key);
  148. if (value && value != "undefined") {
  149. data[key] = value;
  150. }
  151. }
  152. for (var k in data) {
  153. var v = data[k];
  154. if (v == null || typeof v === 'undefined') {
  155. delete data[k];
  156. } else {
  157. if (typeof v === 'string') {
  158. data[k] = $.trim(v);
  159. }
  160. }
  161. }
  162. return data;
  163. }
  164. /**
  165. * option object {'cache', 'loading', 'onTimeout'}
  166. * cache为every、once
  167. */
  168. function post(url, data, callback, option) {
  169. option = option || {};
  170. // 支持postCross(url, callback)的写法;
  171. if ( typeof data == 'function') {
  172. option = callback || {};
  173. callback = data;
  174. data = {};
  175. }
  176. data = _getDefaultData(data);
  177. var xhr = new XMLHttpRequest();
  178. BDY.xhrs.push(xhr);
  179. BDY.xhrCount++;
  180. xhr.index = BDY.xhrs.length;
  181. xhr.open("POST", url);
  182. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  183. xhr.withCredentials = true;
  184. // 兼容ios6.0会缓存
  185. if (window.KalaGame) {
  186. xhr.setRequestHeader("Cache-Control", "no-cache");
  187. }
  188. data = $.param(data);
  189. //获取cache的key
  190. if (option['cache']) {
  191. var cacheKey = 'ajaxCache-' + url + '?' + data;
  192. //如果有cache则不出现loading
  193. var isCached = _loadAjaxCache(cacheKey, callback);
  194. if (isCached) {
  195. option['loading'] = false;
  196. if (option['cache'] == "must") {
  197. return;
  198. }
  199. }
  200. }
  201. if (option['loading']) {
  202. xhr.timeout = 15000;
  203. showLoading();
  204. }
  205. xhr.send(data);
  206. xhr.ontimeout = option['onTimeout'] || function () {
  207. callback && callback({result:0, code:-11, msg:"网络超时,请重试"});
  208. };
  209. // 响应处理
  210. xhr.onload = function() {
  211. BDY.xhrs[xhr.index] = null;
  212. BDY.xhrCount--;
  213. option['loading'] && hideLoading();
  214. var objResult = _getAjaxResult(xhr.responseText);
  215. if (objResult['result'] && option['cache']) {
  216. var cache = localStorage.getItem(cacheKey);
  217. if (cache && cache == xhr.responseText) {
  218. // 网络返回跟缓存一致
  219. return;
  220. } else {
  221. localStorage.setItem(cacheKey, xhr.responseText);
  222. }
  223. }
  224. _handleResult(callback, objResult);
  225. };
  226. }
  227. function get(url, callback, option) {
  228. option = option || {};
  229. var xhr = new XMLHttpRequest();
  230. BDY.xhrs.push(xhr);
  231. BDY.xhrCount++;
  232. var data = {};
  233. _getDefaultData(data);
  234. for (var key in data) {
  235. if (!getParam2(key, url)) {
  236. url += url.indexOf('?') >= 0 ? '&' : '?';
  237. url += key + '=' + data[key];
  238. }
  239. }
  240. xhr.url = url;
  241. option['loading'] && showLoading();
  242. xhr.onreadystatechange = function() {
  243. if (xhr.readyState != 4) {
  244. return;
  245. }
  246. BDY.xhrs[xhr.index] = null;
  247. BDY.xhrCount--;
  248. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && location.protocol == 'file:')) {
  249. option['loading'] && hideLoading();
  250. if (option['type'] == 'text') {
  251. callback(xhr.responseText);
  252. } else {
  253. callback(_getAjaxResult(xhr.responseText));
  254. }
  255. }
  256. };
  257. xhr.open("GET", url);
  258. // xhr.withCredentials = true;
  259. xhr.send();
  260. }
  261. function _getAjaxResult(text) {
  262. var objResult = {};
  263. var objError = {
  264. result : 0,
  265. msg : "系统繁忙,请稍后再试!"
  266. };
  267. try {
  268. objResult = JSON.parse(text);
  269. if (typeof objResult !== 'object' || objResult === null) {
  270. objResult = objError;
  271. }
  272. } catch (ex) {
  273. //非json的处理
  274. objResult = objError;
  275. }
  276. return objResult;
  277. }
  278. function _loadAjaxCache(cacheKey, callback) {
  279. var cache = localStorage.getItem(cacheKey);
  280. if (cache) {
  281. var objResult = JSON.parse(cache);
  282. objResult._fromCache = true;
  283. _handleResult(callback, objResult);
  284. return true;
  285. } else {
  286. return false;
  287. }
  288. }
  289. function _handleResult(callback, objResult) {
  290. //session_id失效,重新验证登录
  291. if(!objResult.result && objResult.code == -5) {
  292. openLogin();
  293. } else {
  294. callback && callback(objResult);
  295. }
  296. }
  297. function _deserialize(value){
  298. if (typeof value != 'string') {
  299. return undefined
  300. }
  301. try {
  302. return JSON.parse(value)
  303. }catch(e) {
  304. return value || undefined
  305. }
  306. }
  307. function getLocalData(key) {
  308. return getParam(key) || _deserialize(localStorage.getItem(key));
  309. }
  310. function setLocalData(key, val) {
  311. localStorage.setItem(key, JSON.stringify(val))
  312. }
  313. function getCookie(name) {
  314. var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  315. if(arr=document.cookie.match(reg))
  316. return unescape(arr[2]);
  317. else
  318. return null;
  319. }
  320. function _setTimeout(callback, timeout) {
  321. var timer = setTimeout(callback, timeout);
  322. BDY.timeout.push(timer);
  323. return timer;
  324. }
  325. function _setInterval(callback, timeout) {
  326. var timer = setInterval(callback, timeout);
  327. BDY.interval.push(timer);
  328. return timer;
  329. }
  330. function _clearRes() {
  331. var len;
  332. var timeout = BDY.timeout;
  333. var interval = BDY.interval;
  334. len = timeout.length;
  335. for (var i = 0; i < len; i++) {
  336. clearTimeout(timeout[i]);
  337. }
  338. len = interval.length;
  339. for (var i = 0; i < len; i++) {
  340. clearInterval(interval[i]);
  341. }
  342. // 重置timer
  343. BDY.timeout = [];
  344. BDY.interval = [];
  345. for (var i in BDY.xhrs) {
  346. BDY.xhrs[i] && BDY.xhrs[i].abort();
  347. }
  348. BDY.xhrs = [];
  349. BDY.xhrCount = 0;
  350. }
  351. // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  352. var loadingDelayHandler = 0;
  353. var loadingTimeoutHandler = 0;
  354. var loadDialog;
  355. function showLoading(text, timeout, cancelable, delay) {
  356. // 超时时间为15s
  357. timeout = timeout || 15000;
  358. // 0.2s后才显示loading
  359. delay = delay || 200;
  360. if (cancelable == null) {
  361. cancelable = true;
  362. } else {
  363. cancelable = !!cancelable;
  364. }
  365. if (loadingDelayHandler) {
  366. return;
  367. }
  368. loadingDelayHandler = setTimeout(function() {
  369. if (!HiydSdk.showLoading(text, timeout, cancelable)) {
  370. Indicator.open(text);
  371. loadingTimeoutHandler = setTimeout(function(){
  372. hideLoading();
  373. showTip("加载超时,请稍后再试");
  374. }, timeout);
  375. }
  376. }, delay);
  377. }
  378. function hideLoading() {
  379. loadingDelayHandler && clearTimeout(loadingDelayHandler);
  380. loadingDelayHandler = 0;
  381. loadingTimeoutHandler && clearTimeout(loadingTimeoutHandler);
  382. loadingTimeoutHandler = 0;
  383. try {
  384. Indicator.close();
  385. } catch(e) {}
  386. }
  387. function showErrorTip(msg, timeout) {
  388. if (!msg) { return; }
  389. timeout = timeout || 3000;
  390. if (!HiydSdk.showErrorTip(msg, timeout)) {
  391. Toast({
  392. message : msg,
  393. position: 'middle',
  394. duration: timeout
  395. });
  396. }
  397. }
  398. function showTip(msg, timeout) {
  399. if (!msg) { return; }
  400. timeout = timeout || 2000;
  401. if (!HiydSdk.showTip(msg, timeout)) {
  402. Toast({
  403. message : msg,
  404. position: 'bottom',
  405. duration: timeout
  406. });
  407. }
  408. }
  409. function showDialog(msg, callback, title, buttonLabels) {
  410. title = title || "提示";
  411. buttonLabels = buttonLabels || "确定";
  412. MessageBox({
  413. title: title,
  414. message: msg,
  415. confirmButtonText: buttonLabels
  416. }).then(action => {
  417. callback && callback(action);
  418. });
  419. }
  420. function confirm(msg, callback, title, buttonLabels) {
  421. title = title || "提示";
  422. buttonLabels = buttonLabels || "确定,取消";
  423. if (!HiydSdk.confirm(msg, callback, title, buttonLabels)) {
  424. MessageBox.confirm(msg, title).then(action => {
  425. callback && callback(true);
  426. }).catch(err => {
  427. callback && callback(false);
  428. });
  429. }
  430. }
  431. function setTitle(title) {
  432. document.title = title;
  433. if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
  434. HiydSdk.run2('setTitle',[title]);
  435. }
  436. // HiydSdk.setTitle(title);
  437. //解决在IOS微信内置浏览器内无法通过document.title修改页面标题的hack
  438. if(checkWXAgent()) {
  439. var $body = $('body');
  440. var $iframe = $('<iframe src="/favicon.ico" style="display:none;"></iframe>');
  441. $iframe.on('load',function() {
  442. setTimeout(function() {
  443. $iframe.off('load').remove();
  444. }, 0);
  445. }).appendTo($body);
  446. }
  447. }
  448. function closeWebView() {
  449. if (!HiydSdk.closeWebView()) {
  450. historyBack();
  451. }
  452. }
  453. function openUrl(url, title, needTopBar) {
  454. if (!HiydSdk.openUrl(url, title, needTopBar)) {
  455. window.open(url);
  456. }
  457. }
  458. function tryAutoLogin() {
  459. if (window.Hiyd) {
  460. var flag = HiydSdk.openLogin();
  461. historyBack();
  462. return flag;
  463. } else {
  464. return false;
  465. }
  466. }
  467. function openLogin() {
  468. var flag = tryAutoLogin();
  469. //调用微信登录接口
  470. if (!flag) {
  471. var fromUrl = encodeURIComponent(document.location.href);
  472. var url = BDY.mHiydUrl + 'user/login?fromUrl=' + fromUrl;
  473. location.href = url;
  474. return false;
  475. }
  476. }
  477. function initWxSdk() {
  478. if(!checkWXAgent()) {
  479. return;
  480. }
  481. let url = BDY.mHiydUrl + "weixin/getJsSign";
  482. let data = {
  483. url : location.href,
  484. appid: 6
  485. };
  486. post(url, data, function(ret) {
  487. ret.data.debug = /test\.|webdev/.test(document.location.href) ? true : false;
  488. ret.data.jsApiList = [
  489. "chooseImage",
  490. "previewImage",
  491. "uploadImage",
  492. ];
  493. wx.config(ret.data);
  494. });
  495. }
  496. function checkWXAgent() {
  497. var ua = navigator.userAgent.toLowerCase();
  498. if (ua.match(/micromessenger/i) == "micromessenger") {
  499. return true;
  500. } else {
  501. return false;
  502. }
  503. }
  504. var lib = {};
  505. lib.getParam = getParam;
  506. lib.getParam2 = getParam2;
  507. lib.setParam = setParam;
  508. lib.setParam2 = setParam2;
  509. lib.removeParam = removeParam;
  510. lib.parseHash = parseHash;
  511. lib.post = post;
  512. lib.get = get;
  513. lib.getLocalData = getLocalData;
  514. lib.setLocalData = setLocalData;
  515. lib.getCookie = getCookie;
  516. lib.setTimeout = _setTimeout;
  517. lib.setInterval = _setInterval;
  518. lib.clearRes = _clearRes;
  519. lib.setTitle = setTitle;
  520. lib.closeWebView = closeWebView;
  521. lib.openUrl = openUrl;
  522. lib.showLoading = showLoading;
  523. lib.hideLoading = hideLoading;
  524. lib.showErrorTip = showErrorTip;
  525. lib.showTip = showTip;
  526. lib.showDialog = showDialog;
  527. lib.confirm = confirm;
  528. lib.checkWXAgent = checkWXAgent;
  529. lib.apiUrl = "http://api.lolbox.duowan.com/api";
  530. lib.staticUrl = "http://static.lolbox.duowan.com";
  531. export default lib;