You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XMLHttpRequest的onreadystatechanged事件始终未触发,请求响应未被Ajax捕获的问题求助

XMLHttpRequest的onreadystatechanged事件始终未触发,请求响应未被Ajax捕获的问题求助

这看起来是个挺普遍的问题,但我刚上手Ajax就踩坑了!翻了好多相关答案都没找到解决办法,试过把onreadystatechanged的定义放在open方法之前和之后,也试过把回调写成单独的函数,换了好几个浏览器都不管用。现在把我最后调试出来的代码放上来,求各位大佬帮忙找找问题出在哪😭

我的代码如下:

<script>
    function sendform() {
        // Creating XMLHttpRequest object
        var qhttp = new XMLHttpRequest();
        // Open the given file
        qhttp.open("POST", "https://localhost:8443/login", true);
        qhttp.onreadystatechange = function() {
            // Creating call back function
            console.log("onreadystate");
            if (qhttp.readyState === 4 && qhttp.status === 200) {
                alert(qhttp.responseText);
            }
            else {
                console.log("error");
                alert("error");
            }
        }
        // Setting HTTP request header
        qhttp.setRequestHeader('Content-type', 'application/json')
        // Sending the JSON document to the server
        name = document.getElementById("username").value;
        pass = document.getElement  ById("password").value;
        qhttp.send(JSON.stringify({
            "username": name,
            "password": pass
        }));
        return false;
    }
</script>

目前的情况是:请求确实发送成功了,所有数据都能传到服务器,但服务器返回的响应直接显示在空白页面上,完全没被Ajax的回调函数捕获到。我到底哪里写错了啊?

备注:内容来源于stack exchange,提问作者bhaber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:24:50