手写ajax

242 阅读1分钟

前言

知识点:

  1. XMLHttpRequest
  2. 状态码
  3. 跨域:同源策略,跨域解决方案

参考文档:developer.mozilla.org/zh-CN/docs/…

GET

// get请求
// xhr.open()第三个参数是一个可选的布尔参数,默认为true,表示要不要异步执行操作。
const xhr = new XMLHttpRequest()
xhr.open('GET','/api', false)
// onreadystatechange,当readystate变化的时候,类似于img.onload、img.onerror
xhr.onreadystatechange = function () {
    // 这里的函数异步执行,可参考之前JS基础中的异步模块
    // 细节:readyState为4
    if (xhr.readyState === 4) {
        // 返回成功状态码为200
        if (xhr.status === 200) {
           // 细节:转为对象
            console.log(JSON.parse(xhr.responseText)
            alert(xhr.responseText)
        }
    }
}
// 发送数据
xhr.send(null)

POST

// post
const xhr = new XMLHttpRequest()
xhr.open('POST', '/login', false)
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            alert(xhr.responseText)
        } else {
            console.log('other')
        }
    }
}
const postData = {
    userName: 'zhangsan',
    password: 'xxx'
}
// 细节:要以字符串的形式发送数据,其它工具已经帮我们转成了字符串
xhr.send(JSON.stringify(postData)

xhr.readState状态码含义

  1. 0---(未初始化)还没有调用send()方法
  2. 1---(载入)已调用send()方法,正在发送请求
  3. 2---(载入完成)send()方法执行完成,已经接收到全部响应内容
  4. 3---(交互)正在解析响应内容
  5. 4---(完成)响应内容解析完成,可以在客户端调用

xhr.status表示http协议的状态码

  1. 2xx --- 表示成功处理请求,如 200
  2. 3xx --- 需要重定向,浏览器直接跳转,如 301:永久重定向, 302:临时重定向,304:资源未改变,浏览器用自身缓存的资源
  3. 4xx --- 客户端请求错误,如404:客户端请求错误,找不到 403:没有权限
  4. 5xx --- 服务端错误