ajax-post.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" id="username"></td>
</tr>
<tr>
<td>密 码:</td>
<td><input type="password" name="possward" id="password"></td>
</tr>
<tr>
<td></td>
<td><button id="btn">提交</button></td>
</tr>
</table>
<script>
var txtUsername=document.getElementById("username");
var txtPassword=document.getElementById("password");
var btn=document.getElementById("btn");
btn.onclick=function(){
var username=txtUsername.value;
var password=txtPassword.value;
var xhr=new XMLHttpRequest();
xhr.open('POSt','login.php');
//如果请求方式为post,并且请求体数据格式为urlencoded格式,必须要设置请求头的格式
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(`username=${username}&password=${password}`);
xhr.onreadystatechange=function(){
if(this.readyState!==4) return;
console.log(this.responseText);
};
}
</script>
</body>
</html>
login.php
<?php
if(empty($_POST['username'])||empty($_POST['password'])){
exit('请输入用户名和密码');
}else{
if($_POST['username']!='admin'||$_POST['password']!='123'){
exit('用户名和密码错误');
}else{
echo '登陆成功';
}
}
?>