AJAX提交表单未刷新,无法正常工作

时间:2019-04-23 04:44:22

标签: php html ajax

当我按“登录”时,脚本将运行并打印出“填写所有字段”(很棒),但似乎在屏幕上回显了它,然后刷新页面。

AJAX:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $("form").submit(function(event){
      var username = $("#username").val();
      var password = $("#password").val();
      var login = $("#login").val();
      $(".formMessage").load("inc/accounts.php",{
        username: username,
        password: password,
        login: login
      });
    });
  });
</script>

表格(仅页面上的表格)

<form method="post" autocomplete="off">
        <div class="form-group"><input class="form-control" type="text" id="username" placeholder="Username" autofocus></div>
        <div class="form-group"><input class="form-control" type="password" id="password" placeholder="Password"></div>
        <div class="form-group"><button class="btn btn-outline-primary btn-block" type="submit" id="login">Login</button></div>
        <p class='formMessage'></p>
        <a href="#" class="forgot">Forgot your password?</a>
        <a href="register" class="forgot">Don't have an account?</a>
    </form>

PHP代码(accounts.php)

if(isset($_POST['login'])){
    $username = $_POST['username'];
    $password = $_POST['password'];

    $date = date("d/m/Y");
    $time = date("h:i a");

    if(empty($username) || empty($password)){
      echo "<span style='color: red;'>Fill in all fields!</span>";
    }elseif(!DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))){
      echo "<span style='color: red;'>Incorrect password/username!</span>";
    }elseif(!password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])){
      echo "<span style='color: red;'>Incorrect password/username!</span>";
    }else{
      $uid = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];

      $cstrong = True;
      $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
      DB::query('INSERT INTO logintokens VALUES(\'\', :token, :uid)', array(':token'=>sha1($token), ':uid'=>$uid));
      setcookie("uid", $token, time() + 60 * 60 * 24 * 5, '/', '.link.com');
      setcookie("uid_", '1', time() + 60 * 60 * 24 * 3, '/', '.link.com');

      echo "<span style='color: green;'>Successfully logged in!</span>";
      echo '<script>window.location.href = "home";</script>';
    }
  }

展示发生了什么的视频:https://gyazo.com/8233450b6493bfe415105ea5dbb61b28

2 个答案:

答案 0 :(得分:2)

您错过了:%s,\(^[FC].*\)\@<=-,/,g,这阻止了元素的默认操作发生。您的最终代码应如下所示:

event.preventDefault()

有关更多信息,您可以访问here

答案 1 :(得分:2)

这对建议

  • 为表单提供一个ID,以便您可以使用$('#formid')进行引用,只是为了便于阅读。
  • 在表单提交的侦听器中,阻止默认操作。

这是一个示例,您已经在代码中传递了事件,因此我们只需要阻止其默认操作(提交+刷新)即可。

...
$(document).ready(function(){
  $("form").submit(function(event){
    event.preventDefault();
...