![](/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.