首页 > Web开发 > 详细

仿jq封装ajax

时间:2018-01-04 15:59:43      阅读:185      评论:0      收藏:0      [点我收藏+]
/**
 * 封装ajax
 */
function ajax () {
  var ajaxData = {
    type: arguments[0].type || ‘GET‘,
    url: arguments[0].url || ‘‘,
    async: arguments[0].async || ‘true‘,
    data: arguments[0].data || null,
    dataType: arguments[0].dataType || ‘text‘,
    contentType: arguments[0].contentType || ‘application/x-www-form-urlencoded‘,
    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
  }
}

  此代码复制自 https://www.cnblogs.com/webSong/p/7224546.html

仿jq封装ajax

原文:https://www.cnblogs.com/handsome-jm/p/8193346.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!