前端登录页面代码
<!DOCTYPE html><html lang="zh-cn"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ajax:FormData案例</title></head><style> * { margin: 0; padding: 0; box-sizing: content-box; } fieldset { max-width: 200px; color: coral; margin: 20px auto; padding: 20px; } input { margin-bottom: 10px; } button { width: 80px; height: 30px; background-color: darkorange; border: none; } button:hover { color: midnightblue; background-color: lightgreen; } button:active { background-color: darkorange; }</style><body> <form action="" method="POST" onsubmit="return false"> <fieldset> <legend>登陆</legend> <label for="username">用户名</label><br> <input type="text" name="username" id="username" required><br> <label for="password">密码</label><br> <input type="password" name="password" id="password" required autofocus><br> <button>提交数据</button> </fieldset> </form> <p></p></body><script> // 1.获取DOM var form = document.querySelector("form"); var btn = document.querySelector("form button"); // 2.按键绑定事件 btn.onclick = function () { // 2.1.创建ajax对象 var xhr = new XMLHttpRequest(); // 2.2.监听请求 xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功返回的数据保存在responseText属性中 var res = JSON.parse(xhr.responseText); console.log(res); // 根据后端返回状态判断 switch (res.status) { case 0: case 1: error = res.message; break; default: error = '未知错误'; } // 将错误信息渲染到页面中 var span = document.createElement("span"); span.innerHTML = error; form.appendChild(span); } } // 3.初始化请求参数:open(请求类型, 请求的地址URL, 是否异步),默认是异步 xhr.open("POST", "demo.php"); // 4.使用表单对象:FormData组织数据 var data = new FormData(form); // 5.发送请求,以json格式发送数据 xhr.send(data); }</script></html>
后端php页面代码(查询数据库验证)
<?php// 加载数据库连接require "db.php";// 接收数据$username = $_POST['username'] ?? null;$password = sha1($_POST['password']) ?? null;// 查询数据$select = "SELECT * FROM `user` WHERE `user_name`=:username AND `password`=:pwd";$data = $pdo->prepare($select);$data->bindParam(':username', $username);$data->bindParam(':pwd', $password);$data->execute();$data->fetch();// 默认返回信息为0$status = 0;// 一般由前端处理html样式,后端只传数据$message = '<span style="color:red">邮箱或密码错误</span>';// 如果查询到匹配的用户,则返回通过信息if ($data->rowCount() == 1) { $status = 1; $message = '<span style="color:green">验证通过</span>';}// 将返回信息转成json字符串echo json_encode(['status' => $status, 'message' => $message]);
运行效果: