正如标题所述,我正在寻找使用JavaScript进行POST请求,并且得到响应。这里是我当前的代码:AJAX POST请求与响应
var request = new XMLHttpRequest();
request.open('POST', 'test.php', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success
console.log(request.responseText)
} else {
// Server-side Error
console.log("Server-side Error")
}
};
request.onerror = function() {
// Connection Error
console.log("Connection Error")
};
request.send({
'color':'red',
'food': 'carrot',
'animal': 'crow'
});
随着test.php的幸福:
<?php
echo $_POST['color'];
?>
这应返回 '红',而是返回任何内容。
这似乎是一个简单的问题,但我只能找到使用jQuery的人的解决方案。我想要一个不依赖于库的解决方案。
**危险**:此代码[易受XSS影响](https://www.owasp.org/index.php/XSS)用户输入在插入HTML文档之前需要转义! – Quentin
**警告**:可以通过查询字符串,发布数据或cookie填充'$ _REQUEST'。命名冲突(特别是涉及cookie时)可能会导致混淆。最好避免使用更明确的superglobals'$ _COOKIES','$ _POST'和'$ _GET'。 – Quentin
是的,我知道这很容易受到XSS的影响 - 我很快把它放在一起,因为我不想上传我的真实代码。 – 073148974301870437087