我正在尝试发送post请求到我的PHP文件,但它说未定义索引。
my js code -
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");
}
my PHP code -
<?php
if(isset($_POST['msg'])){
echo "set";
}
else{
echo "not set";
}
?>
我也尝试了服务器请求方法,但它没有工作
显示未设置,如果我尝试回显$_POST['msg'];
,它会显示未定义索引'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)