Skip to content

基本操作

javascript
// 1.创建 ajax 实例
const xhr = new XMLHttpRequest() // IE 低版本 使用 new ActiveXObject()

/**
 * 2.打开 url
 * 
 * @param {string} method - HTTP 方法。
 * @param {string} url - 请求的 URL。
 * @param {string} [async=true] - 是否执行异步操作,默认为 true。
 * @param {string} [user=null] - 用于认证,当服务器不允许匿名访问时使用,默认为 null。
 * @param {string} password - 同上,默认为 null。
 */
xhr.open('GET', './index.json', true)
// xhr.setRequestHeader('X-Custom-Header', 'value');

// 3.监听 ajax 状态(0、1、2、3、4)
xhr.onreadystatechange = function () {
  const { readyState, status } = xhr

  if (readyState === 4 && /^(2|3)\d{2}$/.test(status)) {
    const respone = xhr.responseText
    const state = xhr.status
  }
}

/**
 * 4.发送请求。如果是异步请求,则此方法会在请求发送后立即返回;如果是同步请求,则此方法
 * 直到响应到达后才会返回。
 * 
 * @param {} [body=null] - 请求体,如果是 GET 或 HEAD 方法,应设置为 null。
 */
xhr.send(null)