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

使用JavaScript向RESTful Web Service发送POST请求无响应问题求助

解决JavaScript POST请求无响应的问题

先看你代码里的几个关键问题,这些是导致请求没响应的主要原因:


修复后的XMLHttpRequest代码

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>AIMS LoginPage</title>
    <script type="text/javascript">
        function validate() {
            let xmlhttp;
            // 修复ActiveX对象拼写错误
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            } else {
                xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
            }

            if (xmlhttp) {
                const username = document.index.Uid.value;
                const password = document.index.pass.value;
                const authDetails = `<?xml version="1.0" encoding="UTF-8"?><credentials><username>${username}</username><password>${password}</password></credentials>`;
                
                // 先绑定状态变化事件,再执行open和send
                xmlhttp.onreadystatechange = function() {
                    if (this.readyState === 4) {
                        // 不要只判断200,也要处理错误状态
                        if (this.status === 200) {
                            document.getElementById("h").innerHTML = this.responseText;
                        } else {
                            document.getElementById("h").innerHTML = `请求失败,状态码: ${this.status}`;
                        }
                    }
                };

                try {
                    xmlhttp.open("POST", "webserviceURIhere", true);
                    xmlhttp.setRequestHeader("Content-type", "text/xml");
                    xmlhttp.send(authDetails);
                } catch (error) {
                    document.getElementById("h").innerHTML = `请求发送出错: ${error.message}`;
                }
            }
        }
    </script>
</head>
<body>
    <!-- 移除不存在的validateForm(),因为按钮是button类型,不需要阻止表单提交 -->
    <form name="index">
        <table>
            <tr>
                <td>UserName </td>
                <td><input type="text" name="Uid" id="Uid" placeholder="Enter Username"></td>
            </tr>
            <br>
            <tr>
                <td>Password </td>
                <td><input type="password" name="pass" id="pass" placeholder="Enter Password"></td>
            </tr>
            <br>
            <tr>
                <td>
                    <input type="button" value="Login" name="submit" onclick="validate()">
                </td>
            </tr>
        </table>
    </form>
    <p id="h"></p>
</body>
</html>

关键修复点说明

  • 变量名不一致:你创建的是xmlhttp,但后续调用open()/send()时用了xhttp,这会直接导致ReferenceError,请求根本发不出去。
  • 事件绑定时机错误:onreadystatechange必须在open()和send()之前绑定,否则可能错过请求完成的状态变化(尤其是请求很快完成时)。
  • ActiveX对象拼写错误:旧IE的对象是ActiveXObject,不是ActiveObject,少了个X。
  • 增加错误处理:原代码只处理了status == 200的情况,现在添加了状态码错误捕获和请求发送时的异常捕获,方便排查问题。
  • 表单优化:移除了不存在的validateForm()回调,因为你的按钮是type="button",不会触发表单提交,不需要额外阻止。

更现代的方案:使用Fetch API

如果你不需要兼容非常老旧的浏览器,推荐用更简洁的Fetch API替代XMLHttpRequest:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>AIMS LoginPage</title>
    <script type="text/javascript">
        async function validate() {
            const username = document.index.Uid.value;
            const password = document.index.pass.value;
            const authDetails = `<?xml version="1.0" encoding="UTF-8"?><credentials><username>${username}</username><password>${password}</password></credentials>`;
            const resultEl = document.getElementById("h");

            try {
                const response = await fetch("webserviceURIhere", {
                    method: "POST",
                    headers: {
                        "Content-Type": "text/xml"
                    },
                    body: authDetails
                });

                if (!response.ok) {
                    throw new Error(`请求失败,状态码: ${response.status}`);
                }

                const responseText = await response.text();
                resultEl.innerHTML = responseText;
            } catch (error) {
                resultEl.innerHTML = `出错了: ${error.message}`;
            }
        }
    </script>
</head>
<body>
    <form name="index">
        <table>
            <tr>
                <td>UserName </td>
                <td><input type="text" name="Uid" id="Uid" placeholder="Enter Username"></td>
            </tr>
            <br>
            <tr>
                <td>Password </td>
                <td><input type="password" name="pass" id="pass" placeholder="Enter Password"></td>
            </tr>
            <br>
            <tr>
                <td>
                    <input type="button" value="Login" name="submit" onclick="validate()">
                </td>
            </tr>
        </table>
    </form>
    <p id="h"></p>
</body>
</html>

Fetch API基于Promise,写法更简洁,异步逻辑更清晰,而且是现代浏览器的标准API。


额外排查点

如果修复后还是没响应,你可以打开浏览器的开发者工具(F12),切换到Network标签,查看请求的状态:

  • 检查请求是否真的发送出去了
  • 查看响应状态码、响应内容
  • 检查是否有跨域问题(CORS错误),如果是跨域,需要后端配置CORS允许你的域名访问

内容的提问来源于stack exchange,提问作者Harsh Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:23:12