使用xhr发起GET数据请求

代码示例:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // 1.创建xhr对象
    var xhr = new XMLHttpRequest()
    // 2.调用OPEN函数 (创建请求)
    xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
    // 3.调用send函数 (发起请求)
    xhr.send()
    //4.监听onreadystatechange事件
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 获取服务器响应的数据
            console.log(xhr.responseText);
        }
    }
</script>

</html>

 

posted @ 2022-05-02 08:57  今天穿秋裤了吗  阅读(382)  评论(0)    收藏  举报