[英]can not get $_POST values in php on ajax request
這是我的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"];
?>
當我在我的localhost上運行這個結果時
注意 :未定義的索引:第2行的C:\\ xampp \\ htdocs \\ chat \\ ajax.php中的名稱
你好
但是當我使用JQuery時它正在正常工作......
我的問題是如何在沒有JQuery的情況下使用JavaScript發送ajax ..?
當您對發布數據使用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>
您可以在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");
更多細節Ajax在w3schools
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.