common.js 8.99 KB
/*
 state
*/
var appState = {
  defaultTime: 120,//默认2分钟倒计时
  countDownTime_timer: null,//支付倒计时
  codeNullTip: "微信授权失败,请您尝试重新扫码 !",//code获取失败提示语
  expandField_1: null,//扩展字段1-备用
  expandObj_1: null,//扩展字段1-备用
}

/*自定义异步请求*/
function ajax() {
  var ajaxData = {
    type: (arguments[0].type || "GET").toUpperCase(),
    url: arguments[0].url || "",
    async: arguments[0].async || "true",
    data: arguments[0].data || null,
    dataType: arguments[0].dataType || "json",
    contentType: arguments[0].contentType || "application/json; charset=utf-8",
    beforeSend: arguments[0].beforeSend || function () {
    },
    success: arguments[0].success || function () {
    },
    error: arguments[0].error || function () {
    }
  }

  ajaxData.beforeSend()
  var xhr = createxmlHttpRequest();
  xhr.responseType = ajaxData.dataType;

  xhr.open(ajaxData.type, ajaxData.url, ajaxData.async);
  xhr.setRequestHeader("Content-Type", ajaxData.contentType);
  xhr.send(convertData(ajaxData.data));

  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        ajaxData.success(xhr.response)
      } else {
        ajaxData.error()
      }
    }
  }
}

function createxmlHttpRequest() {
  if (window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } else if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  }
}

function convertData(data) {
  if (typeof data === 'object') {
    var convertResult = "";
    for (var c in data) {
      convertResult += c + "=" + data[c] + "&";
    }
    convertResult = convertResult.substring(0, convertResult.length - 1)
    return convertResult;
  } else {
    return data;
  }
}

////////////////////////////////demo
//ajax({
//    type: "POST",
//    url: "ajax.php",
//    dataType: "json",
//    data: {
//        "name": "abc",
//        "age": 123,
//        "id": "456"
//    },
//    beforeSend: function () {
//        //some js code
//    },
//    success: function (msg) {
//        console.log(msg)
//    },
//    error: function () {
//        console.log("error")
//    }
//})
/*******common*********/

/*统一请求接口*/
function postRequest(url, params, successCallback, errorCallback) {
  ajax({
    type: "POST",
    url: url,
    dataType: "json",
    data: JSON.stringify(params),
    beforeSend: function () {
      //some js code
    },
    success: function (msg) {
      successCallback(msg);
      //var res = msg;
      //if (res.code == 0) {//进场

      //} else {//其他情况如【该卡号场内已存在】
      //    console.log(res.message);
      //}
    },
    error: function (err) {
      errorCallback(err);
      //console.log("网络地址出错...")
    }
  })
}

/*获取URL?参数*/
function getQueryString(location) {
  //var url = location.search; //获取url中"?"符后的字串
  var url = location.search;
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
    }
  } else {
    theRequest = null;
  }
  return theRequest;
}

/*统一提示信息*/
window.alertMsg = function (txt) {
  var alertFram = document.createElement("DIV");
  alertFram.id = "alertFram";
  alertFram.style.position = "fixed";
  alertFram.style.width = "100%";
  alertFram.style.textAlign = "center";
  alertFram.style.top = "40%";
  alertFram.style.zIndex = "10001";
  strHtml = " <span style=\"font-family: 微软雅黑;display:inline-block;background:#333;color:#fff;padding:0 20px;line-height:36px;border-radius:6px; \">" + txt + "</span>";
  alertFram.innerHTML = strHtml;
  document.body.appendChild(alertFram);
  setTimeout((function () {
    alertFram.style.display = "none";
  }), 2500);
};

//四舍五入保留2位小数(不够位数,则用0替补)
function keepTwoDecimalFull(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    alert('传递参数错误,请检查!');
    return false;
  }
  result = Math.round(num * 100) / 100;
  var s_x = result.toString();
  var pos_decimal = s_x.indexOf('.');
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
  }
  return s_x;
}

/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 *
 * return URL参数字符串
 */
var parseParams = function (data) {
  try {
    var tempArr = [];
    for (var i in data) {
      var key = (i);
      var value = encodeURIComponent(data[i]);//decodeURIComponent
      tempArr.push(key + '=' + value);
    }
    var urlParamsStr = tempArr.join('&');
    return urlParamsStr;
  } catch (err) {
    return '';
  }
};

/*获取对象*/
function getObjectByID(id) {
  return document.getElementById(id);
}

/*秒转时分*/
function formatSeconds(value) {
  var secondTime = parseInt(value);// 秒
  var minuteTime = 0;// 分
  var hourTime = 0;// 小时
  if (secondTime > 60) {//如果秒数大于60,将秒数转换成整数
    //获取分钟,除以60取整数,得到整数分钟
    minuteTime = parseInt(secondTime / 60);
    //获取秒数,秒数取佘,得到整数秒数
    secondTime = parseInt(secondTime % 60);
    //如果分钟大于60,将分钟转换成小时
    if (minuteTime > 60) {
      //获取小时,获取分钟除以60,得到整数小时
      hourTime = parseInt(minuteTime / 60);
      //获取小时后取佘的分,获取分钟除以60取佘的分
      minuteTime = parseInt(minuteTime % 60);
    }
  }
  var result = "" + parseInt(secondTime) + "秒";

  if (minuteTime > 0) {
    result = "" + parseInt(minuteTime) + "分" + result;
  }
  if (hourTime > 0) {
    result = "" + parseInt(hourTime) + "小时" + result;
  }
  return result;
}

/*只能输入数字加字母*/
function checkCharAndNumber(ev) {
  //this.value = this.value.toUpperCase();
  var tmpValue = this.value.replace(/[^\d|chun]/g, '');
  this.value = this.value.toUpperCase();
}

/*检测当前app浏览器*/
function clientBrowserEx() {
  var state = "other";//default
  if (/MicroMessenger/.test(window.navigator.userAgent)) {
    console.log("微信客户端");
    //this.switchShow("wxPay");
    state = "wxPay";
  } else if (/AlipayClient/.test(window.navigator.userAgent)) {
    console.log("支付宝客户端");
    //this.switchShow("aliPay");
    state = "aliPay";
  } else {
    console.log("其他浏览器");
    state = "other";
  }
  return state;
}

/*支付倒计时 @id*/
function countDownTime(id) {
  $obj = getObjectByID(id);
  getObjectByID("headTip").style.display = "block";
  var count = appState.defaultTime;
  appState.countDownTime_timer = setInterval(function () {
    if (count == 0) {
      clearInterval(appState.countDownTime_timer);
      appState.countDownTime_timer = null;
      $obj.innerHTML = count + "秒";
      //删除code后刷新
      window.location.href = funcUrlDel("code");
    } else {
      --count;
      $obj.innerHTML = count + "秒";
    }
  }, 1000);
}

/*删除url中某个参数*/
function funcUrlDel(name) {
  var loca = window.location;
  var baseUrl = loca.origin + loca.pathname + "?";
  var query = loca.search.substr(1);
  if (query.indexOf(name) > -1) {
    var obj = {}
    var arr = query.split("&");
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split("=");
      obj[arr[i][0]] = arr[i][1];
    }
    ;
    delete obj[name];
    var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
    return url
  } else {
    return loca.href;
  }
}

// var userAgent = navigator.userAgent;
// var isAndroid = userAgent.indexOf('Android') > -1 || userAgent.indexOf('Adr') > -1; //android终端
//
// function utilParams(val, orderID, openId) {
//   var _orderTotalFee = Number($('#due').text()) * 100 //总金额
//   var fee = $('#discountFee').text()
//   var _fee = fee.substring(0, fee.length - 1);
//   var _orderDicountFee = Number(_fee) * 100  //优惠了多少钱
//   var _orderActFee = _orderTotalFee - _orderDicountFee  //实收多少钱
//   var jsondata;
//   if (_orderDicountFee > 0) {
//     jsondata = {
//       orderBigType: 100,
//       payOrderType: 101,
//       rltOrderId: orderID,
//       payType: val,
//       terminalSource: 7,
//       orderActFee: _orderActFee,
//       orderTotalFee: _orderTotalFee,
//       orderDicountFee: _orderDicountFee,
//       payUserId: openId,
//       terminalOS: isAndroid ? 'AND' : 'IOS',
//       couponType: 1, //优惠类型
//       couponCode: $('#discountBox').val(),
//     };
//   } else {
//     jsondata = {
//       orderBigType: 100,
//       payOrderType: 101,
//       rltOrderId: orderID,
//       payType: val,
//       terminalSource: 7,
//       orderActFee: _orderActFee,
//       orderTotalFee: _orderTotalFee,
//       payUserId: openId,
//       terminalOS: isAndroid ? 'AND' : 'IOS',
//     };
//   }
//   return jsondata
// }