[英]can not get $_POST values in php on ajax request
Here is my index.html 这是我的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>
And here is my ajax.php 这是我的ajax.php
<?php
echo "Hello " . $_POST["name"];
?>
When I run this on my localhost result is 当我在我的localhost上运行这个结果时
Notice : Undefined index: name in
C:\\xampp\\htdocs\\chat\\ajax.php on line
2
注意 :未定义的索引:第
2行的
C:\\ xampp \\ htdocs \\ chat \\ ajax.php中的名称
Hello你好
But when I am using JQuery It is Working Correctly...
但是当我使用JQuery时它正在正常工作......
And my question is how I send ajax using JavaScript without JQuery..? 我的问题是如何在没有JQuery的情况下使用JavaScript发送ajax ..?
You have to pass proper header information along with request when you use ajax with post data 当您对发布数据使用ajax时,您必须传递正确的标头信息以及请求
<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>
You can use this code in your javascript function. 您可以在javascript函数中使用此代码。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "ajax_test.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Stack&lname=Overflow");
for more details Ajax at w3schools 更多细节Ajax在w3schools
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.