这是我的index.html
<script>
var xml = new XMLHttpRequest();
xml.onreadystatechange = function(){
if (xml.readyState === 4 && xml.status === 200) {
console.log(xml.responseText);
}
}
xml.open("POST", "ajax.php", true);
var data = new FormData();
data.append("name","Sahan");
xml.send(data);
</script>
这是我的 ajax.php
<?php
echo "Hello " . $_POST["name"];
?>
当我在本地主机上运行时,结果是
Notice: Undefined index: name in C:\xampp\htdocs\chat\ajax.php on line 2
Hello
但是当我使用 JQuery 时它工作正常...
我的问题是如何在不使用 JQuery 的情况下使用 JavaScript 发送 ajax...?
最佳答案
当您使用 ajax 发送数据时,您必须将正确的 header 信息与请求一起传递
<script>
var xml = new XMLHttpRequest();
xml.onreadystatechange = function(){
if (xml.readyState === 4 && xml.status === 200) {
console.log(xml.responseText);
}
}
xml.open("POST", "ajax.php", true);
//Send the proper header information along with the request
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
/*var data = new FormData();
data.append("name","Stackoverflow");*/
xml.send("name=Stackoverflow");
</script>
关于javascript - 无法根据 ajax 请求在 php 中获取 $_POST 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47831146/