前端面试题整理——手写AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>手写ajax</title>
</head>
<body>
<script>
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/api', false);
    xhr.onreadystatechange = function () {
        // xhr.readyState 的各个状态
        // 0:未初始化,还没有调用send()方法
        // 1:载入,已调用send()方法,正在发送请求
        // 2:载入完成,send()方法执行完成,已经接收到全部响应内容
        // 3:交互,正在解析响应内容
        // 4:完成,响应内容解析完成,可以再客户端调用
        if(xhr.readyState == 4){
            // status状态码分类:
            // 1xx:服务器收到请求
            // 2xx:请求成功
            // 3xx:重定向
            // 4xx:客户端错误
            // 5xx:服务端错误
            if(xhr.status == 200){
                // 常见状态:
                // 200:成功
                // 301:永久重定向
                // 302:临时重定向
                // 304:资源未被修改
                // 404:资源未找到
                // 403:没有权限
                // 500:服务器错误
                // 504:网关超时
                alert(xhr.responseText)
            }
        }
    }
    xhr.send(null)

    xhr.open('POST','/api',false)
    const postData={
        userName:'zhangsan',
        password:'abc123'
    }
    xhr.send(JSON.stringify(postData))

</script>
</body>
</html>

考点:

1、XMLHttpRequest的使用
2、XMLHttpRequest状态码
3、常见请求状态码
放弃安逸,持续努力——成长
原文地址:https://www.cnblogs.com/MarsPGY/p/13460019.html