http封装ajax请求


var zwt = zwt || {}

zwt.ajax = function (options) {
  // options =  {url:'',method:'',data:'',callback:'',async:''}
  // 默认参数
  options.url = options.url || ''
  options.method = options.method || 'get'
  options.data = options.data || ''
  options.callback = options.callback || ''
  options.async = options.async || true
  // get请求-拼接url
  if (options.method.toLowerCase() == 'get') {
    if (typeof options.data == 'object') {
      var arr = []
      for (var k in options.data) {
        arr.push(k + '=' + options.data[k])
      }
      options.data = arr.join('&')
    }
    options.url += (options.url.indexOf('?' == -1) ? '?' : '') + options.data
  }
  // post请求-转换字符串
  if (options.method.toLowerCase() == 'post') {
    if (typeof options.data == 'object') {
      var arrs = []
      for (var k in options.data) {
        arrs.push(k + '=' + options.data[k])
      }
      options.data = arrs.join('&')
    }
  }
  // 创建发送请求
  var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP') // 兼容ie
  xhr.open(options.method, options.url, options.async)
  if (options.method == 'post') {
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    xhr.send(options.data)
  } else {
    xhr.send(null)
  }
  // 异步请求
  if (options.async == true) {
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        callcall()
      }
    }
  }
  // xhr.abort(); // 取消异步请求
  // 同步请求
  if (options.async == false) {
    callcall()
  }
  // 返回状态判断
  function callcall () {
    if (xhr.status == 200) {
      options.callback(xhr.responseText)
    } else {
      options.callback('error:' + xhr.status + xhr.statusText)
    }
  }
}


使用方法:
zwt.ajax({
      url: HOST + '/api/v1/oauth/token',
      data: {
        appId: appid,
        appSecret: appsecret
      },
      callback: function (res) {
        console.log(res)
      }
    })



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

俊刚、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值