axios的底层ajax,XMLHttpRequest原理解释及使用方法

发布于:2024-07-03 ⋅ 阅读:(16) ⋅ 点赞:(0)

定义

ajax全称asychronous JavaScript and XML

意思是异步的 JavaScript和xml, 也就是通过javascript创建XMLHttpRequest (xhr)对象与服务器进行通信

步骤

创建实例对象,初始请求方法和url,设置监听器监听请求完成状态,发送请求

代码

  <button class="xhrButton">注册</button>
  <script>
    const xhrButton = document.querySelector('.xhrButton')
    xhrButton.addEventListener('click', () => {
       // 传递请求体参数操作,对应axios中的data 数据原理
      // 需设置请求头的contentType内容为json和将对象转为字符串
      //Content-Type=application/json  
      //  application为形容词,应用程序级别的文本格式
      xhr.open('POST', 'http://hmajax.itheima.net/register')
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.addEventListener('loadend', () => {
        console.log(xhr.response.data);

      })
      const user = {
        username: '555',
        password: '666'
      }
      const jsonData = JSON.stringify(user)
      const xhr = new XMLHttpRequest()
      
      // 传递查询参数操作,对应axios封装的params参数

      // 但是,如果有很多的参数我们都得使用多个模板字符串吗?
      // 这里使用到将多个参数转变为查询参数的api
      // const findParmas = {
      //   pa1: 1,
      //   pa2: 2,
      //   pa3: 3
      // }
      //构造函数创建出转换器对象,然后调用toString这个Api
      // const transform=new URLSearchParams(findParmas)
      // const data=transform.toString()

      // xhr.open('GET',`http://xxxxx?${data}`)
      // 这里的第三个参数为是否开启异步请求的布尔值

     
      xhr.send(jsonData)
      // 如果是查询参数则send里不需要填,参数在地址那填入
    })
  </script>

你可以通过使用urlsearchParam路径参数转换器将对象转为查询参数格式a=1&b=2 然后发送,对标axios里的params。

也可以将对象转为json字符串然后设置请求头为json类型的数据作为请求体在最后xhr.send(data)也就是axios里data那玩意发送给服务器

查看请求内容类型

image-20240702172457127