您好!欢迎访问家园网-www.jy.wang!

家园网

XMLHttpRequest发送包含username参数的例子

网络 作者:本站 点击:


代码:

<!DOCTYPE html>
<html>
<head>
    <title>XHR示例</title>
    <script>
        function sendRequest() {
            const username = document.getElementById("username").value;
            const xhr = new XMLHttpRequest();
            
            xhr.open("POST", "https://example.com/api/login", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    document.getElementById("result").innerHTML = 
                        `服务器返回: ${xhr.status} - ${xhr.responseText}`;
                }
            };
            
            // 关键代码:发送拼接后的参数
            xhr.send("username=" + encodeURIComponent(username));
        }
    </script>
</head>
<body>
    <input type="text" id="username" placeholder="输入用户名">
    <button onclick="sendRequest()">提交</button>
    <div id="result"></div>
</body>
</html>

这是一个完整的JavaScript示例,展示如何使用XMLHttpRequest发送包含username参数的POST请求,并模拟服务器响应结果:


示例输出结果(假设输入用户名为"john_doe"):

  1. 请求体内容:username=john_doe

  2. 服务器可能返回(JSON格式):{"status":200,"message":"Login successful"}

关键点说明:

  • 使用encodeURIComponent()防止特殊字符破坏参数结构

  • 必须设置Content-Type请求头

  • 实际开发建议改用更现代的fetch API

  • 此示例需要真实服务器配合测试,或使用开发者工具模拟请求

标签: