批改状态:合格
老师批语:请求的构建与数据的访问, 是api的基础
data.php
<?php$username = $_POST['username'];$password = sha1($_POST['password']);$status = 0;$message = '验证失败,请重试';try {$dsn = "mysql:host=localhost;dbname=phpedu";$pdo = new PDO($dsn, 'root', 'root');$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);// print_r($pdo);} catch (PDOException $e) {print "Error!: " . $e->getMessage() . "<br/>";die();}$sql = "select * from `users` where username=?";// 创建预处理对象$stmt = $pdo->prepare($sql);// $username = 'admin';$stmt->bindParam(1, $username, PDO::PARAM_STR);$stmt->execute() or die(print_r('查询失败' . $stmt->errorInfo()));$res = $stmt->fetch();// print_r($res);if ($res['username'] == $username && $res['password'] == $password) {$status = 1;$message = '验证成功';}echo json_encode(['status' => $status, 'message' => $message], JSON_UNESCAPED_UNICODE);// if ($res['username'] == $username && $res['password'] == $password) {// echo json_encode(['status' => 1, 'message' => '成功'],JSON_UNESCAPED_UNICODE);// }else{// echo json_encode(['status' => 0, 'message' => '失败'],JSON_UNESCAPED_UNICODE);// }
html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><style>input {display: block;margin-bottom: 20px;}</style></head><body><form action="" method="POST" onsubmit="return false"><input type="text" name="username" /><input type="password" name="password" /><button type="submit" name="btn">提交</button></form><span class="info"></span><script>//创建点击事件var btn = document.querySelector("form button");var form = document.querySelector("form");var info=document.querySelector('.info');//false- 默认。事件在冒泡阶段执行btn.addEventListener("click", getData, false);function getData() {//创建ajax对象var xhr = new XMLHttpRequest();//监听事件xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200) {// 请求成功后返回的数据// console.log(xhr.responseText);res = JSON.parse(xhr.responseText);switch (res.status) {case 0:info.style.cssText ="color:red";info.append(res.message)// console.log(res.message);break;case 1:info.style.cssText ="color:blue";info.append(res.message)// console.log(res.message);break;default:console.log("未定义 ");}}};//初始化请求,默认为异步模式xhr.open("POST", "data.php");//加载post请求数据var data = new FormData(form);//发送请求xhr.send(data);}</script></body></html>
初步理解了ajax 异步数据的请求方式
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号