util.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. const formatTime = date => {
  2. const year = date.getFullYear()
  3. const month = date.getMonth() + 1
  4. const day = date.getDate()
  5. const hour = date.getHours()
  6. const minute = date.getMinutes()
  7. const second = date.getSeconds()
  8. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  9. }
  10. const formatNumber = n => {
  11. n = n.toString()
  12. return n[1] ? n : '0' + n
  13. }
  14. let app = getApp();
  15. //返回首页
  16. function goHome(back = false) {
  17. const URL = "/pages/yuesuo/yuesuo"
  18. if (back) {
  19. wx.navigateTo({
  20. url: URL
  21. })
  22. } else {
  23. wx.reLaunch({
  24. url: URL
  25. })
  26. }
  27. }
  28. var loadingNum = 0;
  29. function request(url, method = 'GET', postData, loading = false) {
  30. method = method.toUpperCase();
  31. loadingNum += 1;
  32. if (loading) {
  33. wx.showLoading({
  34. title: '加载中...',
  35. })
  36. }
  37. return new Promise((resolve, reject) => {
  38. wx.request({
  39. url: app.globalData.url + url,
  40. data: postData,
  41. header: {
  42. "Content-Type": "application/x-www-form-urlencoded",
  43. "Accept": "application/json"
  44. },
  45. method: method,
  46. success: function(res) {
  47. resolve(res.data);
  48. },
  49. fail: function(error) {
  50. app.timeOut()
  51. reject(error); //请求失败
  52. },
  53. complete: function() {
  54. loadingNum -= 1;
  55. if (loading && loadingNum < 1) {
  56. wx.hideLoading();
  57. }
  58. }
  59. })
  60. })
  61. }
  62. function getData(url, postData, loading = false) {
  63. return request(url, 'GET', postData, loading = false);
  64. }
  65. function postData(url, postData, loading = false) {
  66. return request(url, 'POST', postData, loading = false);
  67. }
  68. module.exports = {
  69. formatTime,
  70. getData,
  71. postData,
  72. goHome
  73. }