一篇文章搞懂ajax get请求 post请求 以及封装ajax

一、ajax请求

使用传统javascript实现ajax请求需要依赖XMLhttpRequest()对象;

1.XMLhttpRequest对象的方法

①:open(type(get/post),url,true):与服务器建立连接

参数true:代表是否异步,true:异步(99.99%使用true) false:同步(不常用)

②:send()
- get 请求:send(null)
- post 请求:send(参数值)

③:setRequestHeader()
- get请求:不需要设置此方法
- post请求:需要设置

  a:如果请求元素中包含了文件上传 setRequestHeader("Content-Type","multipart/form-data")
  
  b:如果不包含文件上传 setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
2.XMLhttpRequest 对象的属性

①:readyState 请求状态,只有状态为4代表请求完毕

在这里插入图片描述

②:status 相应状态:只有200代表相应正常

在这里插入图片描述

③:onreadystatechange : 回调函数

④:responseText :相应格式为string

⑤:responseXML :相应格式为XML

二、ajax get请求数据
// 第一步:创建XMLHttpRequest对象
let xhr = new XMLHttpRequest()
  // 如果兼容IE6及以下
  // var xhr = null
  // if(window.XMLHttpRequest){
  //   xhr = new XMLHttpRequest()
  // }else{
  //   xhr = new ActiveXObject("Microsoft.XMLHTTP")
  // }

// 第二步:准备发送
xhr.open('get', `url?userName=${userName}`, true)

// 第三步:执行发送

xhr.send(null);

// 第四步:通过回调函数获取数据

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      let result = xhr.responseText;
      console.log(result)
    }
  }
}
三、ajax post请求数据
// 第一步:创建XMLHttpRequest对象
let xhr = new XMLHttpRequest()
  // 如果兼容IE6及以下
  // var xhr = null
  // if(window.XMLHttpRequest){
  //   xhr = new XMLHttpRequest()
  // }else{
  //   xhr = new ActiveXObject("Microsoft.XMLHTTP")
  // }

// 第二步:准备发送
xhr.open('post', `${baseUrl}/posts`, true)

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

let param = `u=${1}&b=${2}`

// 第三步:执行发送

xhr.send(param);

// 第四步:通过回调函数获取数据

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4) {
    if (xhr.status == 200) {
      let result = xhr.responseText;
      console.log(result)
    }
  }
}
四、封装ajax请求 (方式1)
// 封装
    function ajax(method, url, params, done) {
      method = method.toUpperCase()
      var xhr = new XMLHttpRequest()

      if (typeof params === 'object') {
        var tempArr = []
        for (var key in params) {
          var value = params[key]
          tempArr.push(key + '=' + value)
        }
        params = tempArr.join('&')
      }

      if (method === 'GET') {
        url += '?' + params
      }

      xhr.open(method, url, false)

      var data = null
      if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        data = params
      }

      xhr.send(data)

      xhr.onreadystatechange = function () {
        if (this.readyState !== 4) {
          if (this.status == 200) {
            done(this.responseText)
          }
        }
      }

    }

    // 调用
    ajax('get', './time.php', {}, function (res) {
      console.log('hahahahaha')
      console.log(res)
      console.log('做完了')
    })
五、封装ajax请求 (方式2)
// 封装
function $ajax(obj) {
  let data = {
    url: '',
    type: 'get',
    data: {},
    dataType: 'text',
    success: function (result) {}
  }
  for (let key in obj) {
    data[key] = obj[key]
  }
  let xhr = new XMLHttpRequest()

  let params = ''
  for (let attr in data.data) {
    params = params + attr + '=' + data.data[attr] + '&'
  }

  if (params) {
    params = params.substring(0, params.length - 1)
  }

  if (data.type == 'get') {
    xhr.send(null)
  } else if (data.type == 'post') {
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    xhr.send(params)
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        let result = null
        if (data.dataType == 'json') {
          result = xhr.responseText
          result = JSON.parse(result)
        } else if (data.dataType == 'xml') {
          result = xhr.responseXML
        } else {
          result = xhr.responseText
        }
        data.success(result)
      }
    }
  }
}

// 使用
$ajax({
  type,
  url,
  dataType,
  function (res) {
    console.log(res)
  }
})
六、onload

onload 是HTML5 中提供的XMLHttpRequest v2.0定义的(表示加载完成)

// 注意兼容性
xhr.onload = function(){
  console.log(this.readyState)
  console.log(this.status)
}

点击查看 jQuery中对ajax的封装

前端进阶精选:点此去

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值