![](/img/trans.png)
[英]I'm using vanilla js to make a ajax post request to django
[英]using POST in ajax in vanilla js
我正在嘗試將 post 請求發送到我的 PHP 文件,但它說未定義索引。
我的js代碼-
document.getElementById("btn1").addEventListener('click', xh );
function xh(){
xhr = new XMLHttpRequest();
//xhr.open('GET', 'req.php?msg=hello bro', true);
xhr.open('POST', 'req.php');
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
xhr.onprogress = function () {
// document.getElementById("loading").classList.remove("dis");
}
xhr.onload = function () {
console.log(this.responseText);
}
xhr.send("msg=hello");
}
我的 PHP 代碼 -
<?php
if(isset($_POST['msg'])){
echo "set";
}
else{
echo "not set";
}
?>
我也試過服務器請求的方法但是沒用
它顯示未設置,如果我嘗試回顯$_POST['msg'];
它說未定義的索引“味精”
代替
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
你想設置請求頭
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
閱讀更多關於XHR 的信息。 目前的方法是使用fetch() 。
fetch("req.php", {
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: "msg=hello"
}).then(response => response.text())
.then(console.log)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.