A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

原生js的ajax请求
[AppleScript] 纯文本查看 复制代码
// 因为要兼容IE8和IE9,这里就不用Promise了,因为用了之后babel打包瞬间变大
// 创建请求对象
function CreateRequest() {
  try {
    if (window.XMLHttpRequest) {
      return new XMLHttpRequest()
    } else if (window.ActiveXObject) {
      return new ActiveXObject('Microsoft.XMLHTTP')
    }
  } catch (e) {
    console.log(e)
  }
  return null
}
// IE9及IE8不支持CORS跨域请求,针对IE9和IE8做请求兼容
function IE89Request(request) {
  if (IsEmptyObject(request)) {
    return
  }
  request.Method = request.Method == undefined ? 'GET' : request.Method
  if (StringIsNullOrEmpty(request.Url)) {
    return
  }
  if (window.XDomainRequest) {
    var xdr = new XDomainRequest()
    xdr.open(request.Method, request.Url)
    xdr.onerror = function () {
      if (request.ErrorCallback != undefined && typeof (request.ErrorCallback) == 'function') {
        request.ErrorCallback('XDomainRequest error')
      }
    }
    xdr.onload = function() {
      // console.log(xdr.responseText)
      try {
        if (request.SuccessCallback != undefined && typeof (request.SuccessCallback) == 'function') {
          var json = JSON.parse(xdr.responseText)
          request.SuccessCallback(json, xdr)
        }
      } catch (e) {
        // console.log(e, '进入请求error')
        if (request.ErrorCallback != undefined && typeof (request.ErrorCallback) == 'function') {
          request.ErrorCallback(e)
        }
      }
    }
    setTimeout(function () {
      xdr.send(request.Data)
      return xdr
    }, 0)
  }
}

// 数据请求函数封装
function Request (request) {
  if (IsEmptyObject(request)) {
    return
  }
  // 初始化请求属性
  request.Method = request.Method == undefined ? 'GET' : request.Method
  if (StringIsNullOrEmpty(request.Url)) {
    return
  }
  // 默认异步请求
  request.Async = request.Async == undefined ? true : request.Async
  request.Headers = request.Headers == undefined ? {} : request.Headers
  request.DataType = request.DataType == undefined ? 'json' : request.DataType
  request.ContentType = request.ContentType == undefined ? 'application/x-www-form-urlencoded' : request.ContentType
  request.Data = request.Data == undefined ? '' : request.Data
  var xmlHttp = null
  // 创建请求
  xmlHttp = CreateRequest()
  if (xmlHttp == null) {
    return
  }
  // 打开请求
  xmlHttp.open(request.Method, GetUrl(request.Url), request.Async)
  // 设置请求头信息
  xmlHttp.setRequestHeader('Accept', request.DataType)
  xmlHttp.setRequestHeader('Content-Type', request.ContentType)
  for (var key in request.Headers) {
    xmlHttp.setRequestHeader(key, request.Headers[key])
  }
  // 处理请求响应返回
  xmlHttp.onreadystatechange = function () {
    // readyState属性用来表示请求的状态,有5个可取值,分别是:
    // “0”:表示未初始化,即对象已经建立,但是尚未初始化(尚未调用open()方法);
    // “1”:表示正在加载,此时对象已建立,尚未调用send()方法;
    // “2”:表示请求已发送,即send()方法已调用;
    // “3”:表示请求处理中;
    // “4”:表示请求已完成,即数据接收完毕。
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        if (request.SuccessCallback != undefined && typeof (request.SuccessCallback) == 'function') {
          var data
          if (request.DataType == 'json') {
            data = JSON.parse(xmlHttp.responseText)
          } else if (request.DataType == 'xml') {
            data = xmlHttp.responseXML
          } else {
            data = xmlHttp.responseText
          }
          request.SuccessCallback(data, xmlHttp)
        }
      } else {
        if (request.ErrorCallback != undefined && typeof (request.ErrorCallback) == 'function') {
          request.ErrorCallback(xmlHttp)
        } else {
          if (StringIsNullOrEmpty(xmlHttp.responseText)) {
            alert(xmlHttp.status + ':' + xmlHttp.statusText)
          } else {
            alert(xmlHttp.responseText)
          }
        }
      }
    }
  }
  // 发送请求
  xmlHttp.send(request.Data)
  return xmlHttp
}

// POST数据请求
function PostRequest (url, data, successCallback, errorCallback, asyncs) {
  var request = {}
  var xmlHttp = null
  request.Url = url
  request.Method = 'POST'
  request.Async = asyncs
  request.ContentType = 'application/json; charset=utf-8'
  request.Data = JSON.stringify(data)
  request.SuccessCallback = function (a, b) {
    request.IsCallback = true
    successCallback && successCallback(a, b)
  }
  request.ErrorCallback = function (a) {
    request.IsErrorCallback = true
    errorCallback && errorCallback(a)
  }
  if (IEVersion() == 8 || IEVersion() == 9) {
    xmlHttp = IE89Request(request)
  } else {
    xmlHttp = Request(request)
  }
  return xmlHttp
}
调用
[JavaScript] 纯文本查看 复制代码
let params = {name:'haorooms',value:'ajaxTest'}
api_haoroomsData(params, function(res){
 // 请求结果
}, funcrion(error){
// 错误结果
})



0 个回复

您需要登录后才可以回帖 登录 | 加入黑马