无需jQuery,如何通过AJAX向控制器发送POST参数?
原生JS实现AJAX发送POST参数到控制器
没问题,我来帮你把POST参数补充到代码里!用原生XMLHttpRequest发送POST请求其实只需要两个关键步骤,我直接给你修改好的完整代码,再一步步解释:
首先,你需要做两件核心的事:
- 设置正确的请求头,告诉服务器你发送的是表单格式的数据
- 把参数按照规范格式编码后,传给
send()方法
修改后的完整代码如下:
function myFunction() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("myDiv").innerHTML = this.responseText; } }; // 1. 先打开请求,再设置请求头:表单类型POST数据需要指定Content-Type xhr.open("POST", "my_controller.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 2. 准备POST参数:格式为key1=value1&key2=value2,特殊字符必须编码 var params = "username=" + encodeURIComponent("Jacopo") + "&email=" + encodeURIComponent("test@example.com"); // 3. 发送编码后的参数 xhr.send(params); }
<button type="button" onclick="myFunction()">Send POST parameters</button> <div id="myDiv"></div>
关键细节说明:
- 请求头设置:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")是必须的,否则服务器可能无法正确解析你的POST参数(这是浏览器表单提交的默认内容类型)。 - 参数编码:用
encodeURIComponent()处理每个参数值,能避免空格、中文或者特殊字符导致的解析错误——比如参数值是Hello World!,编码后会变成Hello%20World%21,服务器能正确识别。 - 如果参数数量多,建议用对象组织再转成拼接字符串,更易于维护:
var formData = { username: "Jacopo", email: "test@example.com" }; var params = Object.keys(formData) .map(key => `${key}=${encodeURIComponent(formData[key])}`) .join("&");
在你的my_controller.php里,就可以用$_POST['username']和$_POST['email']直接获取这些参数啦!
内容的提问来源于stack exchange,提问作者JacopoStanchi
相关产品推荐
相关产品推荐

