[英]unable to get POST data in php 'undefined index' error
我正在對Ajax請求使用普通的javascript。 通過post方法php發送數據時拋出錯誤。
index.php
<html>
<header>
<script>
function submit(){
var userName = document.getElementById("username").value;
var passWord = document.getElementById("password").value;
var data = "username=" + userName + "&password=" + passWord;
//send ajax request
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
console.log(xmlHttp.responseText);
}
}
xmlHttp.open("post", "validateuser.php");
xmlHttp.send(data);
}
</script>
</header>
<body>
<label>User Name : </label>
<input type="text" name="username" id="username"/>
<label>Password : </label>
<input type="text" name="password" id="password"/>
<button onClick="submit()"> Login</button>
</body>
</html>
validateuser.php
<?php
$userName = $_POST["username"];
$password = $_POST["password"];
echo $userName . $password;
在用於發布的Javascript ajax中,您需要在代碼中添加以下行:
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
您可以查看文檔和示例W3schools和開發人員mozilla
為了獲得更可靠的代碼,只需將以下行添加到您的php代碼中
if(isset($_POST['username']) && isset($_POST['password'])){
//your code
}
您需要在xmlHttp
對象上設置標題。 在xmlHttp.send(data);
之前添加以下行xmlHttp.send(data);
行:
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.