Ajax-XMLHttpRequest

XMLHttpRequest是浏览器内置的一个构造函数

作用:基于 new 出来的 XMLHttpRequest 实例对象,可以发起 Ajax 的请求。

axios 中的 axios.get()、axios.post()、axios() 方法,都是基于 XMLHttpRequest(简称:XHR) 封装出来的!

使用 XMLHttpRequest 发起请求

我们可以不用 axios 封装的 Ajax 函数,直接基于 XMLHttpRequest 发起 Ajax 请求。

1、创建 xhr 对象

2、调用 xhr.open() 函数

3、调用 xhr.send() 函数

4、监听 load 事件

 XMLHttpRequest 发起 GET请求 (不带参数)

 // 准备对象
    const xhr = new XMLHttpRequest()
    // 准备数据: xhr.open(方式,地址,同步或异步 默认是异步)
    xhr.open('get','http://ww.liulongbin.top:3009/api/get')
      // 发送数据
    xhr.send()
      // 监听onload事件
    xhr.addEventListener('load',function(){
      console.log(xhr.response);
    })

 

XMLHttpRequest 发起 GET请求 (带参数)

可以在请求的 URL 地址后面通过 ? 的形式携带查询参数

 let xhr = new XMLHttpRequest()
      xhr.open('get','http://www.liulongbin.top:3009/api/get?name=毛毛&age=18')
      xhr.send()
      xhr.addEventListener('load',function(){
        console.log(xhr.response);
      })

XMLHttpRequest 发起 POST请求(携带请求体数据

        当需要携带请求体数据时,需要进行额外的两步操作:

                在 xhr.open() 之后,调用 xhr.setRequestHeader() 函数,指定请求体的编码格式

                在 xhr.send() 中,指定要提交的请求体数据

 let xhr = new XMLHttpRequest()
      xhr.open('post','http://www.liulongbin.top:3009/api/post')
       // 指定编码格式
      xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
      // 指定要提交的请求体数据
      xhr.send('name=rose&age=21')
      xhr.addEventListener('load',function(){
        console.log(xhr.response);
      })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值