You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中调用PHP数据库接口实现登录页账号密码实时校验

实现方案

你需要把表单提交到当前页面做校验,验证通过后再创建Session跳转,修改逻辑如下:

1. 核心逻辑调整

  • 表单提交地址改为当前页面,不直接跳转到业务页
  • 页面顶部PHP增加POST请求处理逻辑,完成数据库校验、Session创建、跳转的全流程
  • 校验失败时在当前页直接展示错误提示

2. 完整修改后代码

<?php 
session_start();
$error = '';

// 处理表单POST提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 后端先做参数校验
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    if (empty($username) || empty($password)) {
        $error = '请填写完整的账号密码';
    } else {
        // 连接数据库
        try {
            $pdo = new PDO('mysql:host=localhost;dbname=ausleihe;charset=utf8mb4', 'root', '');
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // 使用预处理语句防SQL注入,禁止直接拼接SQL
            $stmt = $pdo->prepare("SELECT * FROM login WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // 密码校验(如果你的密码是明文存储的可以直接判断,强烈建议后续改成哈希存储)
            // 哈希存储校验写法:if ($user && password_verify($password, $user['password']))
            if ($user && $password === $user['password']) {
                // 校验通过,创建Session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                // 跳转到目标页面
                header('Location: searchpage.php');
                exit;
            } else {
                $error = '账号或密码错误';
            }
        } catch (PDOException $e) {
            $error = '系统错误,请稍后重试';
            // 开发环境可以打开下面的注释看错误详情
            // $error = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <title>Login</title>
    <link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="jquery.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="wrapper fadeInDown">
        <div id="formContent">
            <!-- Icon -->
            <div class="fadeIn first">
                <img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
            </div>

            <!-- Login Form action改为当前页面 -->
            <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="validateForm(event);">
                <input type="text" id="login" class="fadeIn second" name="username" placeholder="username" value="<?php echo htmlspecialchars($username ?? ''); ?>">
                <input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
                <input type="submit" class="fadeIn fourth" value="Log In">
            </form>

            <div id="formFooter">
                <a class="underlineHover" style="color:red" id="warning">
                    <?php echo htmlspecialchars($error); ?>
                </a>
            </div>
        </div>
    </div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
  var input_username = document.getElementById("login");
  var input_password = document.getElementById("password");
  if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
    event.preventDefault();
    document.getElementById("warning").innerHTML = "Fill empty fields!";
  }
  else {
    return true;
  }
}
</script>

3. 注意事项

  • 禁止使用原SQL拼接写法,必须用PDO预处理语句,避免SQL注入漏洞
  • 不要明文存储用户密码,注册时使用password_hash()加密密码,登录时用password_verify()校验,安全性更高
  • 后续可以给Session增加安全配置,比如开启httponly、secure属性,防范Cookie劫持风险

内容的提问来源于stack exchange,提问作者GetGetCoded

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:54:00