【JS】原生 js 发送 AJAX

164 阅读1分钟

下面只作简单的实现

const url = "/Server"

// 1. 创建 xhr 对象
const xhr = new XMLHttpRequest()

// 2. 建立 http 连接
// 参数分别为 请求方式,请求地址,是否异步(默认异步)
xhr.open('get', url, true)

// 3. 绑定状态监听函数
xhr.onreadystatechange = function(){
    // readyState 有 5 种状态
    // 0:还未调用 open()
    // 1:已经调用 open(),但还未调用
    // 2:已经调用 send(),尚未接收到数据
    // 3:正在接收数据,尚未接收完毕
    // 4:已经成功接收所有数据
    if(xhr.readyState !== 4) return
    
    // 如果状态码为 2 开头的,或者是 304(缓存重定向),表示请求成功
    if(xhr.status % 100 === 2 || xhr.status === 304){
        handler(xhr.responseText)
        // handler(xhr.responseXML)
    } else {
        console.log(xhr.statusText)
    }
}

// 4. 绑定错误监听函数
xhr.onerror = function(){
    console.error(xhr.statusText)
}

// 5. 设置请求头信息
xhr.setRequestHeader('Accept', 'application/json')

// 6. 设置接收数据的格式
xhr.responseType = 'json'

// 7. 发送请求
xhr.send()