首页 > 解决方案 > ajax 错误 checkUsn 未在 HTMLInputElement.onkeyup 中定义

问题描述

我正在做连接到 mysql 数据库的登录表单,我想检查用户名是否存在于数据库中而不重新加载整个页面。我正在使用 Ajax 从服务器发送和接收数据。现在我被这个错误困住了,“checkUsn 没有在 HTMLInputElement.onkeyup 中定义”。有人可以帮我弄这个吗?我试过用谷歌搜索,但我的代码似乎是正确的。这是我的代码

function checkUsn(){
    var usn = document.getElementById("usn").value;
    if(usn){
        $.ajax({
            type: 'post',
            url: 'checkdata.php',
            data: {
                emp_username: usn,
            },
            success: function(response){
                $('#status').html(response);
                if (response == "OK"){
                    return: true;
                }else{
                    return false;
                }
            }
        });
    }else{
        $('#status').html("INCORRECT USN AND PW");
        return false;
    }
}

校验数据.php

<?php
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);

if(isset($_POST['emp_username'])){
    $usn = $_POST['emp_username'];

    $checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";

    $query = mysqli_query($conn, $checkdata);

    if(mysqli_num_rows($query) > 0){
        echo "OK";
    }else{
        echo "Your Username not exist";
    }
    exit();
}
?>

这是我的表格

  <form class="modal-content animate" action="/login_action.php" method="post" onsubmit="return checkall();">
    <div class="container">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
      <img class="avatar img-responsive col-lg-6 col-md-6 col-sm-6 col-xs-6" src="img/employee_avatar.png" alt="Avatar">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3"></div>
    </div>
    <div class="container">
      <label for="usn"><b>Username</b></label>
      <input id="usn" type="text" placeholder="Enter Username" name="usn" onkeyup="checkUsn();" required>

      <label for="pw"><b>Password</b></label>
      <input type="password" placeholder="Enter Password" name="pw" required>

      <button type="submit">Login</button>
      <label>
        <input type="checkbox" checked="checked" name="remember"> Remember me
      </label>
    </div>

    <div class="container" style="background-color:#f1f1f1">
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
      <span class="psw">Forgot <a href="#">password?</a></span>
    </div>
    <button type="button" onclick="btnClickTest()"> test </button>
    <span id="status"> </span>
  </form>

先感谢您!

标签: javascriptphpjqueryajax

解决方案


Try to change you success function like this :


   success: function(response){
                $('#status').html(response);
                if (response == "succeed"){
                    return: true;
                }else{
                    return false;
                }
            }

推荐阅读