common.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. Array.prototype.remove = function (val) {
  2. var index = this.indexOf(val);
  3. while (index > -1) {
  4. this.splice(index, 1);
  5. index = this.indexOf(val);
  6. }
  7. }
  8. Array.prototype.clear = function () {
  9. //this.length = 0;
  10. this.splice(0, this.length)
  11. }
  12. Array.prototype.addAll = function ($array) {
  13. if ($array == null || $array.length == 0)
  14. return;
  15. for (var $i = 0; $i < $array.length; $i++)
  16. this.push($array[$i]);
  17. }
  18. Array.prototype.insertAll = function ($array) {
  19. if ($array == null || $array.length == 0)
  20. return;
  21. $array = $array.reverse()
  22. for (var $i = 0; $i < $array.length; $i++)
  23. this.splice(0, 0, $array[$i]);
  24. }
  25. // 对Date的扩展,将 Date 转化为指定格式的String
  26. // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
  27. // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  28. // 例子:
  29. // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  30. // (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  31. // (new Date(timestamp)).Format("yyyy/M/d h:m") 毫秒转日期
  32. Date.prototype.Format = function (fmt) { //author: meizz
  33. if(!fmt) fmt = 'yyyy-MM-dd hh:mm:ss'
  34. var o = {
  35. "M+": this.getMonth() + 1, //月份
  36. "d+": this.getDate(), //日
  37. "h+": this.getHours(), //小时
  38. "m+": this.getMinutes(), //分
  39. "s+": this.getSeconds(), //秒
  40. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  41. "S": this.getMilliseconds() //毫秒
  42. };
  43. if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  44. for (var k in o)
  45. if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  46. return fmt;
  47. }
  48. function getCookie(name) {
  49. var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  50. if (arr = document.cookie.match(reg))
  51. return unescape(arr[2]);
  52. else
  53. return null;
  54. }
  55. function setCookie(name, value, days) {
  56. days = days || 90;
  57. var exp = new Date();
  58. exp.setTime(exp.getTime() + days * 86400 * 1000);
  59. document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
  60. }
  61. function isEmpty(str) {
  62. return str == null || str == undefined || str == ''
  63. }
  64. function locationPage(url, check_returnurl) {
  65. if (check_returnurl) {
  66. var returnurl = getUrlQueryVal('returnurl')
  67. if (returnurl) url = returnurl
  68. }
  69. location.href = url
  70. }
  71. function localReplace(url) {
  72. location.replace(url)
  73. }
  74. function locationBack(isRefresh) {
  75. if(history.length <= 1) locationPage('/h5/views/qbtask/list.html?type=1')
  76. else {
  77. if(isRefresh && document.referrer) location.href = document.referrer
  78. else history.back()
  79. }
  80. }
  81. function showWeuiDialog($selector, clickFun) {
  82. $($selector).show()
  83. $($selector + ' .weui-mask').addClass('weui-mask--visible')
  84. $($selector + ' .weui-dialog').addClass('weui-dialog--visible')
  85. $($selector + ' .weui-mask').unbind('click').click(function () {
  86. hideWeuiDialog($selector)
  87. })
  88. $($selector + ' .weui-dialog__btn').unbind('click').click(function () {
  89. var index = $(this).index()
  90. if (clickFun) clickFun(index)
  91. })
  92. $($selector + ' .weui-dialog-close').unbind('click').click(function () {
  93. hideWeuiDialog($selector)
  94. })
  95. }
  96. function hideWeuiDialog($selector) {
  97. $($selector + ' .weui-mask--visible').removeClass('weui-mask--visible')
  98. $($selector + ' .weui-dialog--visible').removeClass('weui-dialog--visible')
  99. }
  100. function showLoading(text) {
  101. //myApp.hideIndicator();
  102. //myApp.showIndicator();
  103. if (text == null) text = ''
  104. $.showLoading(text)
  105. }
  106. function hideLoading() {
  107. //$('.preloader-indicator-overlay, .preloader-indicator-modal').fadeOut(400, function () {
  108. // myApp.hideIndicator();
  109. //})
  110. // $('.preloader-indicator-overlay, .preloader-indicator-modal').remove();
  111. $.hideLoading()
  112. }
  113. function showTip(msg, cbk, delay) {
  114. if (!delay) delay = 1500
  115. $.toast.prototype.defaults.duration = delay
  116. $.toast(msg, 'text', cbk)
  117. }
  118. function showTopTip(msg, delay) {
  119. if (!delay) delay = 1500
  120. $.toptip(msg, delay, 'success');
  121. }
  122. function showTopTipError(msg, delay) {
  123. if (!delay) delay = 1500
  124. $.toptip(msg, delay, 'error');
  125. }
  126. function successConfirmBack(ret) {
  127. var msg = '提交成功'
  128. if (ret && ret.info) msg = ret.info
  129. $.alert(msg, undefined, function () {
  130. history.back();
  131. });
  132. }
  133. function successConfirmLoad(ret, url) {
  134. var msg = '提交成功'
  135. if (ret && ret.info) msg = ret.info
  136. $.alert(msg, undefined, function () {
  137. locationPage(url);
  138. });
  139. }
  140. function apiGet(url, data, callback, loadingstyle, nohint) {
  141. apiRequest(url, data, callback, 'get', loadingstyle, nohint)
  142. }
  143. function apiPost(url, data, callback, loadingstyle, nohint, isformdata) {
  144. apiRequest(url, data, callback, 'post', loadingstyle, nohint, isformdata)
  145. }
  146. /**
  147. *
  148. * @param url
  149. * @param data
  150. * @param callback
  151. * @param loadingstyle 0 none 1 preloader 2 indicator
  152. * @param nohint
  153. */
  154. function apiRequest(url, data, callback, method, loadingstyle, nohint, isformdata) {
  155. if (url.indexOf('http') != 0 && url.indexOf('/') != 0) {
  156. // url = HOST + url
  157. }
  158. if (!method) method = 'get'
  159. if (!data) data = {}
  160. // data['openid'] = getOpenId()
  161. // data['timestamp'] = parseInt(new Date().valueOf() / 1000)
  162. //data['openid'] = getOpenId()
  163. if (loadingstyle == undefined || loadingstyle == null) {
  164. //loadingstyle = 1
  165. }
  166. if (loadingstyle == 1) showLoading();
  167. else if (loadingstyle == 2) showLoading();
  168. if (isformdata) {
  169. var formdata = new FormData()
  170. for (var k in data) {
  171. formdata.append(k, data[k])
  172. }
  173. data = formdata
  174. }
  175. var options = {
  176. type: method,
  177. url: url,
  178. data: data,
  179. dataType: 'json',
  180. error: function (res) {
  181. if (!nohint) $.alert("请求失败...");
  182. // 加载完毕需要重置
  183. hideLoading();
  184. if (callback) callback(null, -1);
  185. },
  186. success: function (data) {
  187. if (data.code != 0) {
  188. if (!nohint) $.alert(data.msg);
  189. }
  190. hideLoading()
  191. if (callback) callback(data, data.code);
  192. }
  193. }
  194. if (isformdata) {
  195. options['processData'] = false
  196. options['contentType'] = false
  197. }
  198. $.ajax(options);
  199. }
  200. function getUrlQueryVal(name, def) {
  201. var reg = new RegExp("(^|&|\\?)" + name + "=([^&]*)(&|$)");
  202. var url = window.location.href
  203. var value = null
  204. var r = url.substr(1).match(reg);
  205. if (r != null) value = decodeURIComponent(r[2]);
  206. if (value == null && def) value = def
  207. return value;
  208. }
  209. // function getOpenId() {
  210. // return getCookie('openid')
  211. // }
  212. AM = {
  213. initWeixin: function (jsApiList, callback) {
  214. AM.getWxSignPackage(function (data) {
  215. wx.config({
  216. "appId": data["appId"],
  217. "timestamp": data["timestamp"] + '',
  218. "nonceStr": data["nonceStr"],
  219. "signature": data["signature"],
  220. // "debug": true,
  221. "jsApiList": jsApiList
  222. });
  223. if (callback) callback()
  224. })
  225. },
  226. getWxSignPackage: function (callback) {
  227. if (!navigator.userAgent.match(/MicroMessenger/i)) {
  228. return
  229. }
  230. apiGet("api/user/get_wx_sign_package", {
  231. "url": location.href
  232. }, function (result) {
  233. // alert(JSON.stringify(result))
  234. callback(result.data);
  235. });
  236. },
  237. // 会话缓存 expire 秒
  238. sessionCache: function (key, val, expire) {
  239. var timestamp = parseInt(new Date().getTime() / 1000);
  240. var data
  241. if (val == undefined || val == null) {
  242. data = sessionStorage.getItem(key)
  243. if (!data) return null
  244. data = JSON.parse(data)
  245. if (data.expire > 0 && timestamp - data.t > data.expire) {
  246. sessionStorage.removeItem(key)
  247. return null
  248. }
  249. return data.val
  250. }
  251. if (!expire) expire = 0
  252. data = {
  253. t: timestamp,
  254. expire: expire,
  255. val: val
  256. }
  257. sessionStorage.setItem(key, JSON.stringify(data))
  258. },
  259. getSessionCache: function (key, defaultval) {
  260. var val = this.sessionCache(key)
  261. if (val == null) val = defaultval
  262. return val
  263. }
  264. }
  265. function initWxConfig(callback) {
  266. var title = document.title
  267. var link = location.href
  268. var icon = ''
  269. if (typeof wx == 'undefined') return
  270. AM.initWeixin([
  271. "onMenuShareTimeline",
  272. "onMenuShareAppMessage",
  273. "onMenuShareQQ",
  274. "onMenuShareQZone",
  275. 'chooseImage',
  276. 'previewImage',
  277. 'uploadImage',
  278. 'downloadImage',
  279. 'getLocalImgData',
  280. 'scanQRCode',
  281. // 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice',
  282. // 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice'
  283. ], function () {
  284. //alert('share init...')
  285. if (callback) callback()
  286. })
  287. }
  288. // 微信JDK选择图片
  289. function wxChooseImage(callback, count) {
  290. wx.chooseImage({
  291. count: count || 9,
  292. sizeType: ['original', 'compressed'],
  293. sourceType: ['album', 'camera'],
  294. success: function (res) {
  295. // res.localIds.toString(); 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
  296. setTimeout(function () {
  297. callback(res['localIds']);
  298. }, 100);
  299. }
  300. });
  301. }
  302. function wxImageSrc(localId, cbk) {
  303. var imgsrc = localId
  304. var u = navigator.userAgent
  305. var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  306. //alert(wx.getLocalImgData)
  307. if (isIOS && wx.getLocalImgData) {
  308. wx.getLocalImgData({
  309. localId: localId,
  310. success: function (res) {
  311. var imgsrc = res.localData;
  312. //alert(imgsrc)
  313. imgsrc = imgsrc.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg')
  314. cbk(imgsrc)
  315. }
  316. });
  317. } else {
  318. cbk(imgsrc)
  319. }
  320. }
  321. function wxUploadImage(callback, count) {
  322. count = count || 1
  323. var uploadcount = 0
  324. var mediaids = []
  325. var localsrc = []
  326. var localIds = []
  327. wxChooseImage(function (_localIds) {
  328. localIds = _localIds.toString().split(',')
  329. uploadNext()
  330. }, count);
  331. function uploadNext() {
  332. var localid = localIds[uploadcount]
  333. //alert(localid)
  334. wxImageSrc(localid, function (src) {
  335. localsrc.push(src)
  336. wx.uploadImage({
  337. localId: localid,
  338. isShowProgressTips: 1,
  339. success: function (res) {
  340. uploadcount++
  341. mediaids.push(res['serverId'])
  342. if (uploadcount < localIds.length) {
  343. uploadNext()
  344. } else {
  345. if (callback) callback(mediaids, localsrc)
  346. }
  347. }
  348. });
  349. })
  350. }
  351. }
  352. // 上传头像
  353. function wxUploadAvatar(element, callback) {
  354. wxChooseImage(function (localIds) {
  355. wx.uploadImage({
  356. localId: localIds.toString(),
  357. isShowProgressTips: 1,
  358. success: function (res) {
  359. var url = $(element).data("url")
  360. if (!url) url = '/api/user/upload_avatar'
  361. apiGet(url, {
  362. wxServerIds: res['serverId']
  363. }, function (ret, err) {
  364. //if(err) return
  365. // $(element).attr("src", ret.data.urls[0]);
  366. if (callback) callback(ret, err)
  367. });
  368. }
  369. });
  370. }, 1);
  371. }
  372. function transformToJson(form){
  373. var formData = $(form).serializeArray()
  374. var obj={}
  375. for (var i in formData) {
  376. if(formData[i].name != '') obj[formData[i].name]=formData[i]['value'];
  377. }
  378. return obj;
  379. }