【Ajax】- Native XMLHttpRequest

1. What is XMLHttpRequest

It is a built-in constructor of the browser. Function : Based on the XMLHttpRequest instance object created by new, Ajax requests can be initiated. The axios.get(), axios.post(), and axios() methods in axios are all encapsulated based on the asynchronous operation of XMLHttpRequest (XHR for short) ! Please think about it: Can we initiate Ajax requests directly based on XMLHttpRequest without using Ajax functions encapsulated by axios? Answer: Absolutely!

2. Use XMLHttpRequest to initiate a GET request

The main 4 implementation steps: 1. Create an xhr object 2. Call the xhr.open() function, which is equivalent to the request line of the message 3. Call the xhr.send() function, which is equivalent to the request body of the message 4. Monitor the load event server The data format returned to the client is a json format string, so JSON.parse() is required

// 1、创建 xhr 对象
 let xhr = new XMLHttpRequest();
 // 2、调用 **xhr.open()** 函数
 xhr.open('GET', 'http://xxx.com/api/xx');
 // 3、调用 **xhr.send()** 函数       get方式没有请求体
 xhr.send();
 // 4、监听 load 事件  load事件,也可以放到 前面
 xhr.addEventListener('load', function () {
   console.log(JSON.parse(this.response));       // 服务器响应给客户端
 })

Initiate a get request without parameters and with parameters in the native way

 let btn = document.querySelector('button')
    btn.addEventListener('click', function() {
 // 1.创建异步对象
      let xhr = new XMLHttpRequest()
 ​
 // 2.使用异步对象发起请求:准备好请求报文
 // 2.1 请求行:请求方式和请求url,通过open方法可以设置请求行
      xhr.open('get', 'http://www.itcbc.com:3006/api/getbooks')
 // 如果需要带参数,则需要在url拼接:
 // xhr.open('get', 'http://www.itcbc.com:3006/api/getbooks?id=12163')
 ​
 // 2.2 请求头: 编码格式,get方式不需要设置请求头,因为get方式的参数只能在url拼接,它有默认的编码格式:UTF-8
 // 2.3 请求体:传递给服务器的参数,get方式的参数应该在url中拼接,所以get方式没有请求体,但是也需要调用send方法,可以不传递参数或者传递null
      xhr.send(null)
        
 // 3.使用异步对象接收响应
 // xhr.response:就是响应体
 // 当响应完成了,数据可以使用了,就会自动的触发一个load事件,在这个事件中就可以正确的获取到服务器的响应数据
      xhr.addEventListener('load', function() {
   // 如果不出意外,服务器返回给客户端的数据格式是json格式字符串
      console.log(JSON.parse(xhr.response), typeof JSON.parse(xhr.response))
    })
 })

The core object that initiates an Ajax request isXMLHttpRequest

Get the data returned by the server response through loadevents , xhr.response(response body)

URL parameters can only be spliced ​​after the URL address

The request body, put it in send(), such as: send(request body)

detail:

1. The get method does not have a request body, but it also needs to call the send method, which can pass no parameters or pass null

2. When the response is completed and the data can be used, a load event will be automatically triggered, and the response data of the server can be correctly obtained in this event.

3. If there is no accident, the data format returned by the server to the client is a json format string

To submit request body data, you need to specify the Content-Type header

When you need to submit the request body data, you need to call the xhr.setRequestHeader() function after xhr.open() to specify the encoding format of the request body

 let xhr = new XMLHttpRequest();
 xhr.addEventListener('load', function () {
   console.log(this.response);
 })
 // 将请求参数拼接到url后面
 xhr.open('POST', 'http://www.itcbc.com/api/post');
 ​
 // 根据请求体格式的不同,需设置对应的Content-Type头
 xhr.setRequestHeader('Content-Type', '值')
 ​
 xhr.send('username=zs&age=20');

Initiate post request in native mode

detail:

1. Parameters cannot be passed in the url and can only be set in the send() request body

2. Be sure to set the request header setRequestHeader(), and the set request header format should correspond to the parameters of what format you pass

3. The format of the passed parameter is key=value&key=value. If it is an object, it needs to be converted into json format, and the request header format also needs to be replaced in the same way.

 let btnadd = document.querySelector('.btnadd')
 let bookname = document.querySelector('[name="bookname"]')
 let author = document.querySelector('[name="author"]')
 let publisher = document.querySelector('[name="publisher"]')
 ​
 btnadd.addEventListener('click', function() {
 // 收集数据
 let booknameV = bookname.value
 let authorV = author.value
 let publisherV = publisher.value
 ​
 // 创建异步对象
  let xhr = new XMLHttpRequest()
 ​
 // 发起请求
 // 请求行:post不能在请求行中拼接参数,否则相当于没有传递
  xhr.open('post', 'http://www.itcbc.com:3006/api/addbook')
     
 // 请求头:post方式传递普通键值对,需要设置Content-type编码格式,否则后台无法正确的获取到参数
 // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
 // json格式,上面的是字符串格式
  xhr.setRequestHeader('Content-Type', 'application/json')
     
 // 请求体,参数格式与get一样,除非你进行其它的处理
 // xhr.send(`bookname=${booknameV}&author=${authorV}&publisher=${publisherV}`)
 // 需要对象方式提交,则需要转换JSON,否则会报错,请求头也需要更换json
    xhr.send(
        JSON.stringify({
          bookname: booknameV,
          author: authorV,
          publisher: publisherV
        })
    )
 ​
 // 接收响应
 xhr.addEventListener('load', function() {
      console.log(JSON.parse(xhr.response))
    })
 })

In order to facilitate the server to receive data, when submitting the request body, you need to specify a request header called Content-Type

Request body format Content-Type Does it need to be specified in the code
parameter=value & parameter=value application/x-www-form-urlencoded Yes
'{ "id": 1, "name": "zs" }' application/json Yes
new FormData() multipart/form-data; xxxxxxxxx random characters No, the browser automatically sets it

When using axios, you don't need to care about this request header, because axios has already handled the matter of adding the request header for us, but to write native code, you need to specify it yourself

Guess you like

Origin blog.csdn.net/m0_55960697/article/details/124308870