window.location.href don't work with AJAX

window.location.href don't work with AJAX

本文关键字:work with AJAX location href don window      更新时间:2023-09-26

不知什么原因,window.location.href"函数不适合我,似乎找不到原因。这是index.php中的代码:

<div class="dropdown-menu">
    <div style="width: 300px;">
        <div class="panel panel-primary">
            <div class="panel-heading">Login</div>
            <div class="panel-heading">
                <label for="email">Email</label>
                <input class="form-control" id="email"  name="email" required />
                <label for="password">Password</label>
                <input type="password" class="form-control" id="password"  name="password" required />
                <p><br/></p>
                <a href="#">Forgotten Password</a><input type="button" class="btn btn-success" name="login" id="login" value="Login">
            </div>
        </div>
        <div class="panel-footer"></div>
    </div>
</div>

这是"action.php"中的函数

<?php
if(isset($_POST["userLogin"])){
    $email = mysqli_real_escape_string($con, $_POST["userEmail"]);
    $password = md5($_POST["userPassword"]);
    $sql = "SELECT * FROM user_info WHERE email = '$email' AND password = '$password'";
    $run_query = mysqli_query($con, $sql);
    if($run_query===false){
        echo mysqli_error($con);
    } else {
        $row = mysqli_fetch_array($run_query);
        $_SESSION["uid"]= $row["user_id"];
        $_SESSION["name"]= $row["first_name"];
        echo "welcome";
    }
}
?>

这是jQuery的AJAX函数:

$(document).ready(function(){
    $("#login").click(function(event){
        event.preventDefault();
        var email =  $("#email").val();
        var pass = $("#password").val();
        
        $.ajax({
            url : "action.php",
            method : "POST",
            data : {userLogin: 1, userEmail:email, userPassword:pass},
            success : function(data){
                if(data == "welcome"){
                    window.location.href = "profile.php";
                }
               /* alert(data);*/
            }
        });
    });
});

指出:正如您在jQuery函数中看到的那样,这里有:"alert(data);"我想看看它是否有效,然后把它放在屏幕上,不带"window.location.href"函数看到的"if"表述是正确的,它确实成立。此外,当我直接进入profile.php文件时,我看到用户已登录,这意味着对我来说SQL函数工作正常,只是它不会重定向到(profile.php)页面。

window.location.href期望一个绝对url或相对于您的域名的url(如果它以/开头)。

如果你只想改变当前路径的文件部分,你可以使用window.location.assign("profile.php")

如果你想在同一域名内重定向

window.location.href = "/profile.php";

如果你想重定向到另一个域

window.location.href = "http://www.antotherdomainname.com/profile.php";