簡體   English   中英

成功登錄后如何使用jQuery將用戶重定向到主頁

[英]How to redirect the user to the home page with jQuery after successful login

我是jQuery的新手,我在login.js文件中使用post方法向login.php腳本發送請求,並根據輸入的表單數據的性質檢索錯誤消息。

我的所有錯誤消息都正常工作,並在瀏覽器中正確顯示。 我的問題是,當用戶輸入有效的登錄憑據時,我想將它們重定向到主頁。 相反,jQuery將我的結果用於成功登錄並將其插入login_error div。

我出錯的任何想法?

login.js

$(document).ready(
function login_error()
{
    $("#login").click(function(event)
    {
        event.preventDefault();
        var postData = $('#login_form').serialize();

        $.post('login.php', postData, function(result)
        {   
            if(result != "match"){
                $('#login_error').html(result);
            }else{
                window.location = 'home.php';
            }
        });
    });
});

login.php

<?php 

include "core/init.php";

$username = $password = "";

if(isset($_POST['username']) && isset($_POST['password'])){

    $username = $_POST['username'];
    $password = $_POST['password'];

    if(empty($username) || empty($password)){
        echo '<p class="alert-danger">You didn\'t fill in all the fields.</p>';
    }else if(user_exists($username) === false){ 
        echo '<p class="alert-danger">The username you entered doesn\'t match any account in our records. Sign up for an account.</p>';
    }else if(user_verified($username) === false){
        echo "<p class='alert-danger'><strong>".$username."</strong>&nbspis not a verified username. Check your inbox for a verification email.</p>";
    }else if(check_details($username, $password) === false){
        echo '<p class="alert-danger">The login details you entered don\'t match our records.</p>';
    }else{
        log_in($username, $password);
    }

}else{
    echo '<p class="alert-danger">Oops - something broke! We\'re working to fix this, check back soon.</p>';
}

?> 

我的log_in函數:

function log_in($username, $password){

    $db   = mysqli_connect('localhost', 'root', '', 'forum');
    $sql  = "SELECT user_id FROM users WHERE username = ?";
    $stmt = mysqli_prepare($db, $sql);

    if($stmt){
        mysqli_stmt_bind_param($stmt, 's', $username);
        mysqli_stmt_bind_result($stmt, $user_id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_fetch($stmt);

        if(!empty($user_id)){
            $_SESSION['id']   = $user_id;
            $_SESSION['user'] = $username;
            echo 'match';
        }else{
            return false;
        }
    }
}

如果您的剩余代碼工作正常,則只需使用window.location.href = "home.php";更改window.location代碼window.location.href = "home.php"; 這里href用於位置重定向

你可以使用header("Location: home.php"); 在php登錄功能上成功。 喜歡:

    if(!empty($user_id)){
        $_SESSION['id']   = $user_id;
        $_SESSION['user'] = $username;
        header("Location: home.php");
    }else{
        return false;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM