Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:传统的ajax技术已非常成熟了, 很好用的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ajax-json-formdata用户信息验证</title>
</head>
<body>
<p>请登录:</p>
<form
action=""
method="POST"
style="display: grid; gap: 15px;"
onsubmit="return false"
>
<input
type="email"
name="email"
placeholder="exam@email.com"
required
autofocus
/>
<input type="password" name="password" placeholder="******" required />
<button>提交</button>
</form>
<script>
// 1. 获取表单和按钮
var form = document.querySelector("form");
var btn = document.querySelector("form button");
// 2. 给按钮绑定事件
btn.onclick = function () {
// 1. 创建ajax对象
var xhr = new XMLHttpRequest();
// 2. 监听请求
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// console.log(xhr.responseText);
var res = JSON.parse(xhr.responseText);
console.log(res);
// 根据后端返回的状态进行判断
switch (res.status) {
case 0:
case 1:
error = res.message;
break;
default:
error = "未知错误";
}
// 将error信息渲染到页面中
var span = document.createElement("span");
span.innerHTML = error;
form.appendChild(span);
}
};
// 3. 初始化请求参数
xhr.open("POST", "test5.php");
// 4. 使用FormData来组织数据,最终仍是以表单数据方式发送
var data = new FormData(form);
// data.append("email", form.email.value);
// data.append("passowrd", form.password.value);
// 5. 发送请求, 发送到服务器上的是json格式字符串
xhr.send(data);
};
</script>
</body>
</html>
<?php
// print_r($_POST);
$users = [
['id'=>1,'email'=>'melinda@php.cn', 'password'=>'123'],
['id'=>2,'email'=>'micki@qq.com', 'password'=>'123'],
];
$status = 0; $message = '<span style="color:red">邮箱或密码错误</span>';
// $status = 0; $message = '邮箱或密码错误';
foreach ($users as $user) {
if ($user['email'] == $_POST['email'] && $user['password'] == $_POST['password']) {
$status = 1;
$message = '<span style="color:green">验证通过</span>';
// $message = '验证通过';
}
}
echo json_encode(['status'=>$status, 'message'=> $message]);
POST
请求流程:new XMLHttpRequest()
onreadystatechange
open()
FormData
来组织数据send()