代码:
<!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"):
请求体内容:
username=john_doe服务器可能返回(JSON格式):
{"status":200,"message":"Login successful"}
关键点说明:
使用
encodeURIComponent()防止特殊字符破坏参数结构必须设置
Content-Type请求头实际开发建议改用更现代的
fetch API此示例需要真实服务器配合测试,或使用开发者工具模拟请求