ajax-php login案例
时间:2021-04-10 13:29:37
收藏:0
阅读:0
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input{
height:100px;
}
input[name]{
width:200px;
}
input[name=username]{
border:5px double green;
}
[name=password]{
color:blue;
}
</style>
</head>
<body>
<form action="./fa/zx">
<h2 style="display:none;"></h2>
username: <input type="text" name="username" autocomplete="off"><br/>
password: <input type="text" name="password" autocomplete="off"><br/>
<button>submit</button>
</form>
<div name="password" style="height:400px;">flajsdlfk</div>
<div name="com">fdlafd</div>
<a href="" name="com">flaksjdfllfasjdf</a>
<script>
const username=document.querySelector(‘input[name=username]‘)
const password=document.querySelector(‘input[name=password]‘)
const form=document.querySelector(‘form‘)
const h2=document.querySelector(‘h2‘)
form.addEventListener(‘submit‘,e=>{
e.preventDefault()
if(!username.value) return alert(‘username empty‘)
if(!password.value) return alert(‘password empty‘)
const xhr=new XMLHttpRequest()
xhr.open(‘POST‘,‘./login.php‘)
xhr.onload=function(){
const{message,code}=JSON.parse(this.responseText)
if(code===0){
h2.innerHTML=‘success‘
h2.style.display=‘block‘
}else if(code===2){
h2.innerHTML=‘failed‘
h2.style.display=‘block‘
}else if(code===1){
h2.innerHTML=‘incomplete‘
h2.style.display=‘block‘
}
}
xhr.setRequestHeader(‘content-type‘,‘application/x-www-form-urlencoded‘)
xhr.send(`username=${username.value}&password=${password.value}`)
})
</script>
</body>
</html>
PHP
<?php
if(!isset($_POST[‘username‘]) || !isset($_POST[‘password‘])){
$arr=array(
"message"=>"error !",
"code"=>1
);
echo json_encode($arr);
exit;
}
$username=$_POST[‘username‘];
$password=$_POST[‘password‘];
$link=mysqli_connect(‘localhost‘,‘root‘,‘cruces‘,‘abate‘);
$sql="select * from users where username=‘$username‘ and password=‘$password‘";
$result=mysqli_query($link,$sql);
$data=mysqli_fetch_all($result,MYSQLI_ASSOC);
if(count($data)){
$arr=array(
"message"=>‘success‘,
"code"=>0
);
}else{
$arr=array(
"message"=>" login failed",
"code"=>2
);
};
echo json_encode($arr);
exit;
?>
评论(0)