ajax请求的五个步骤

461 阅读1分钟

1.创建一个XMLHttpRequest异步对象
2.设置请求方式和请求地址
3.接着,用send发送请求
4.监听状态变化
5.最后,接收返回的数据

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>13545565712</title>
</head>

<body>
    <script>
        function getchange() {
            //  01-创建对象,判断是否为现代浏览器,处理兼容性问题
            var xmlhttp;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            //  02-判断状态码
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.body.innerHTML = xmlhttp;
                }
            };
            // 03-设置获取方式,获取数据
            xmlhttp.open('get', 'aaa.json', true);
            // 04-发送请求
            xmlhttp.send();
        }
    </script>
    <p onclick="getchange()">点我试试</p>
</body>

</html>

原文地址:blog.csdn.net/ZXH0122/art…