Skip to content

XMLHTTPRequest

介绍

  • 原生 JavaScript API:XHR 是浏览器原生提供的 API,用于进行异步通信。
  • 回调风格:XHR 使用回调函数的方式来处理异步操作,通常需要设置 onreadystatechange 事件回调。
  • 老式,不够现代:相对较老,不支持 Promise 风格的编程,对于复杂的异步操作可能显得不够现代化。

CRUD

read list

js
const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://reqres.in/api/users?page=2', true)
xhr.onreadystatechange = e => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    const response = JSON.parse(xhr.response)
    console.log(response)
  }
}
xhr.onerror = e => {
  console.error(e)
}
xhr.send()

read single

js
// 'https://reqres.in/api/users/2'
const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://reqres.in/api/users?page=2', true)
xhr.onreadystatechange = e => {
  if (xhr.readyState == 4 && xhr.status == 200) {
    const response = JSON.parse(xhr.response)
    console.log(response)
  }
}
xhr.onerror = e => {
  console.error(e)
}
xhr.send()

create

js
// 'https://reqres.in/api/users'

update

js
// 'https://reqres.in/api/users/2'

delete

js
// 'https://reqres.in/api/users/2'

withCredentials 属性 - MDN

js
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://example.com/', true)
xhr.withCredentials = true
xhr.send(null)

参阅


xhr 封装(第三方库)

jQuery.ajax()

jQuery Ajax 是 jQuery 库的一部分,封装了底层的 XMLHttpRequest,提供了更高级的接口,隐藏了许多底层细节,以简化异步请求的处理。

常见问题

全局设置
js
$.ajaxSetup({
  beforeSend: function (xhr) {
    // 这里可以统一为所有请求发送 token、lang 等等公共参数
  },
  complete: function (xhr, status) {
    // 这里可以为所有响应做统一的处理,例如:权限问题、网络问题等等
    if (xhr.status == 401) {
      // ...
    } else if (xhr.status == 403) {
      // ...
    }
  },
})
非 GET 请求中优雅地传递 query 参数
js
const params = decodeURIComponent($.param({ key1: 'value1', key2: 'value2' }))
const data = { otherKey: 'otherValue' }
const url = `https://example.com/api?${params}`
$.ajax({
  url,
  type: 'POST',
  data,
  success(data, status, xhr) {},
  error(xhr, status, error) {},
  complete(xhr, status) {},
})

Axios

Axios 是一个基于 promise 网络请求库,作用于 node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和 node.js 中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

基于 MIT 许可发布