login.php
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
</head>
<body>
<h2>用户登录</h2>
<p><input type="text" name="user" value=""></p>
<p><input type="password" name="pwd" value=""></p>
<button>登录</button>
</body>
<script>
var btn=document.getElementsByTagName('button')[0];
btn.onclick=function(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
var p=document.createElement('p');
var msg=JSON.parse(xhr.responseText);
if(msg['state']==1){
p.innerHTML=msg['msg'];
}
if(msg['state']==0){
p.innerHTML=msg['msg'];
}
p.style.color='red';
document.body.appendChild(p);
setTimeout(function(){
document.body.removeChild(p);
},2000)
}else{
alert('response fail'+xhr.status)
}
}
}
xhr.open('post','check.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
var data={
user:document.getElementsByName('user').item(0).value,
pwd:document.getElementsByName('pwd').item(0).value
}
var jsondata=JSON.stringify(data);
console.log(jsondata);
xhr.send('data='+jsondata);
}
</script>
</html>
check.php
<?php
//print_r($_POST);
$userdata=['user'=>'55308442@qq.com','pwd'=>'q123456'];
$data=json_decode($_POST['data'],true);
if( $data['user']==$userdata['user'] && $data['pwd']==$userdata['pwd']){
$msgbox=['state'=>1,'msg'=>'登录成功'];
exit(json_encode($msgbox));
}else{
$msgbox=['state'=>0,'msg'=>'用户名密码错误'];
exit(json_encode($msgbox));
}