JavaSctipt Ajax请求过程

131 阅读1分钟
function ajax() {
    /**
     * 1 创建 XMLHttpRequest 对象
     */
    const xhr = new XMLHttpRequest();

    /**
     * 2 创建请求
     * method 请求类型 example:GET
     * url 请求地址
     * async 是否异步
     */
    xhr.open(method, url, async)

    /**
     * 2.5 请求状态
     */
    xhr.onprogress = () => {
        // xhr.readyState
    }

    /**
     * 3 异步处理
     * status http请求结果 200表示请求成功
     * readyState 异步请求状态 4表示完成
     */
    xhr.onreadystatechange = () => {
        if (xhr.status === 200 && xhr.readyState === 4) {
            // 处理结果
        }
    }

    /**
     * 4 发送请求
     */
    xhr.open()

    /**
     * 注意 post请求时要设置content-type
     * xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
     */
}