下载APP

ajax


theme: devui-blue

判断数据类型:Object.prototype.toString.call()

  • { } -> '[object Object]'
  • [ ] ->'[object Array]'
  • function( ){ } -> '[object Function]'
  • null -> '[object Null]'
  • undefined -> '[object undefined]'
  • 123 -> '[object Number]'
  • '123' -> '[object String]'
  • true -> '[object boolean]'

封装ajax 结合promise

function ajax(option) {
  let {
    timeout = 0, //超时
    type = 'get', //请求方式
    cached = 'true', //缓存
    dataType = 'text', //返回数据格式
    url, //地址
    data //参数
  } = option
 
  return new Promise((resolve, reject) => {
    // 创建xhr
    let xhr = new XMLHttpRequest()
    // 设置超时(毫秒)
    xhr.timeout = timeout
    // data支持查询字符串和对象
    if (Object.prototype.toString.call(data) === '[object Object]') {
      // data对象转换成查询字符串
      let str =''  //abc=123&a=456
      for (let key in data) {
        str += key+'='+data[key]+'&'
      }
      // 清除最后一个&符
      data = str.substr(0,str.length-1)
    }
    // 请求方式
    if (type.toLowerCase() === 'get') {
      // 是否缓存
      let time = ''
      !cached && (time = '_='+Date.now())
      // 初始化
      xhr.open(type, url+'?'+data+time,true)
      // 发送请求
      xhr.send(null)
    }
    else if (type.toLowerCase() === 'post') {
      // 初始化
      xhr.open(type, url)
      // 设置响应头
      xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
      // 发送请求
      xhr.send(data)
    }
    else {
      throw new Error('目前只支持get和post请求')
    }
    // 等待响应状态改变
    xhr.onreadystatechange = function () {
      if(xhr.readyState === 4){
        if (xhr.status >= 200 && xhr.status < 300) {
          if (dataType === 'xml') {
            resolve(xhr.responseXML)
          }
          else if (dataType === 'json') {
            let json = JSON.parse(xhr.responseText)
            resolve(json)
          }
          else if (dataType === 'text') {
            resolve(xhr.responseText)
          }
        }
        else {
          reject(xhr.status)
        }
      }
    }
  })

}
在线举报