ajax请求没有反应


<!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>
    <button id="get">GET</button>
    <br>
    <button id="post">POST</button>
    <br>
    <div id="div"></div>
</body>
</html>

<script>
    window.onload = function(){
        const get = document.querySelector('#get')
        const post = document.querySelector('#post')
        const div = document.querySelector('#div')
        get.onclick = function(){
            console.log('点击了get按钮')  //当点击按钮之后这里执行了
            let xhr = new XMLHttpRequest()
            xhr.onreadystatechange = function(){
                console.log('asd')  //当点击按钮之后这里没有执行
                if(this.readyState == 4 && this.status ==200){
                    div.innerHTML = this.responseText
                }
                xhr.open('GET','http://127.0.0.1/api/get?a=1',true)  //跨域了,应该会有一个报错吧,但是没反应
                xhr.send()
            }
        }
    }
</script>

这样试试看。

<!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>
    <button id="get">GET</button>
    <br>
    <button id="post">POST</button>
    <br>
    <div id="div"></div>
</body>

</html>

<script>
    window.onload = function () {
        const get = document.querySelector('#get')
        const post = document.querySelector('#post')
        const div = document.querySelector('#div')
        get.onclick = function () {
            console.log('点击了get按钮')  //当点击按钮之后这里执行了
            let xhr = new XMLHttpRequest()
            xhr.onreadystatechange = function () {
                console.log('asd')  //当点击按钮之后这里没有执行
                if (this.readyState == 4 && this.status == 200) {
                    div.innerHTML = this.responseText
                }
            }
            xhr.open('GET', 'http://127.0.0.1/api/get?a=1', true)  //跨域了,应该会有一个报错吧,但是没反应
            xhr.send()
        }
    }
</script>