[英]using POST in ajax in vanilla js
I am trying to send the post request to my PHP file but it is saying undefined index.我正在尝试将 post 请求发送到我的 PHP 文件,但它说未定义索引。
my js code -我的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");
}
my PHP code -我的 PHP 代码 -
<?php
if(isset($_POST['msg'])){
echo "set";
}
else{
echo "not set";
}
?>
I also tried the server request method but it didn't work我也试过服务器请求的方法但是没用
it is showing not set, and if I try to echo the $_POST['msg'];
它显示未设置,如果我尝试回显$_POST['msg'];
it says undefined index 'msg'它说未定义的索引“味精”
Instead of代替
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
you want to set the request header你想设置请求头
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Read more aboutXHR .阅读更多关于XHR 的信息。 The present approach it to use fetch() though.目前的方法是使用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.