正如標題所述,我正在尋找使用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