weixin_45724811 2022-05-06 18:34 采纳率: 100%
浏览 165
已结题

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>
  • 写回答

1条回答 默认 最新

  • 林一怂儿 前端领域新星创作者 2022-05-06 19:35
    关注

    这样试试看。

    <!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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月14日
  • 已采纳回答 5月6日
  • 创建了问题 5月6日

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法