摘要:1. 登錄頁面(login.html)<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>ajax與json進(jìn)行無刷新表單驗證</title></
1. 登錄頁面(login.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax與json進(jìn)行無刷新表單驗證</title>
</head>
<body>
<h3>用戶登錄</h3>
<form action="">
<p><input type="text" name="username" id="username" placeholder="用戶名"></p>
<p><input type="password" name="password" id="password" placeholder="密碼"></p>
<p><button type="button" onclick="login()">登錄</button></p>
</form>
<script>
function login() {
let btn = document.getElementsByTagName('button')[0];
let username = document.getElementsByName('username')[0];
let password = document.getElementsByName('password')[0];
/*console.log(username.value.length);
if (username.value.length == 0) {
let span = document.createElement('span');
span.style.color = 'red';
span.innerText('用戶名不能為空');
document.username.append(span);
}*/
// 1.創(chuàng)建xhr對象
let xhr = new XMLHttpRequest();
// 2.監(jiān)聽響應(yīng)狀態(tài)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let p = document.createElement('p');
p.style.color = 'red';
let json = JSON.parse(xhr.responseText);
if (json.code === 1) {
p.innerHTML = json.msg;
document.forms[0].appendChild(p);
btn.disabled = true;
setTimeout(function () {
document.forms[0].removeChild(p);
btn.disabled = false;
if (json.code == 1) {
location.href = 'inc/admin.php';
}
}, 2000)
}else {
p.innerHTML = json.msg;
document.forms[0].appendChild(p);
btn.disabled = true;
setTimeout(function () {
document.forms[0].removeChild(p);
btn.disabled = false;
return false;
}, 2000)
}
}
};
//3.設(shè)置請求參數(shù)
xhr.open('post','inc/check.php',true);
//4.設(shè)置請求頭信息,將內(nèi)容類型設(shè)置為表單提交方式
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//5.發(fā)送請求
let data = {
username: username.value,
password: password.value
};
let data_json = JSON.stringify(data);
xhr.send('data='+data_json);
}
</script>
</body>
</html>
2.驗證代碼(check.php)
<?php
//echo json_encode('測試數(shù)據(jù)');
$user = json_decode($_POST['data']);
$name = trim($user->username);
$password = sha1(trim($user->password));
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
$sql = "SELECT COUNT(*) FROM `user` WHERE `name`=:name AND `password`=:password ";
//$sql = "SELECT COUNT(*) FROM `user` WHERE `email`='{$email}' AND `password`='{$password}' ";
$stmt = $pdo->prepare($sql);
$stmt->execute(['name'=>$name,'password'=>$password]);
$res = $stmt->fetchColumn(0);
if ($res ==1) {
exit(json_encode(['code'=>1,'msg'=>'登錄成功,正在跳轉(zhuǎn)...']));
} else {
exit(json_encode(['code'=>0,'msg'=>'郵箱或密碼錯誤,登錄失敗']));
}
批改老師:查無此人批改時間:2019-05-16 09:09:45
老師總結(jié):完成的不錯,json數(shù)據(jù)可以在不同的編程語言中傳遞數(shù)據(jù)。好好練習(xí),繼續(xù)加油