简体   繁体   English

在来自 PHP 的 JQuery AJAX 请求之后重定向

[英]Redirecting after JQuery AJAX request from PHP

So when the login button is clicked, I use JQuery POST method to get data from login.php if the login was successful or not.所以当登录按钮被点击时,我使用 JQuery POST 方法从 login.php 获取数据,如果登录成功与否。 If it wasn't (no user found), then it correctly displays the message.如果不是(未找到用户),则它会正确显示消息。

But when I want to redirect the user (user exists), it prints out the whole webpage into that one DIV.但是当我想重定向用户(用户存在)时,它会将整个网页打印到那个 DIV 中。

The JQuery after button is pressed:按下按钮后的 JQuery:

$(function(){

$("#login-form").submit(function() {
    event.preventDefault();

    var name = $('#inputName').val();
    var password = $('#inputPassword').val();

    $.post("login.php", 
    {
        name: name,
        password: password
    },
    function(data)
    {
        $("#resultDiv").hide().html(data).fadeIn(1000).effect( "shake", {direction:"up",times:2, distance:10}, 750 );
    });
});
});

If login not successful, it displays.如果登录不成功,则显示。 But when I want to redirect, doesen't work:但是当我想重定向时,不起作用:

if(!$row) {
echo '<div class="alert alert-danger" style="margin-top:25px; margin-bottom: 0px; text-align:center;">Invalid <strong>username</strong> or <strong>password</strong>.</div>';
} else {

  $line = mysqli_fetch_assoc($query);

  $_SESSION['IP'] = $line["IP"];
  $_SESSION['ID'] = $line["ID"];
  $_SESSION['username'] = $username;

  header("location:choose.php");
}

So when the user logs in, how do I just redirect him?那么当用户登录时,我该如何重定向他呢? Don't want to display anything.不想显示任何东西。

Your login script won't redirect the whole page the way you have it, it is only redirecting the AJAX request, so it makes sense that the whole page ends up in the resultDiv.您的登录脚本不会按照您拥有的方式重定向整个页面,它只会重定向 AJAX 请求,因此整个页面最终出现在 resultDiv 中是有道理的。

Your success function should look at the data returned before it applies the data to the resultDiv html().您的成功函数应该在将数据应用于 resultDiv html() 之前查看返回的数据。

I found it easier to make the login response a JSON data set, which makes it much easier to grab:我发现将登录响应设为 JSON 数据集更容易,这使得获取更容易:

if(data.loggedIn==true) {
  window.location = data.location;
} else {}

You can also keep the resultDiv for errors, it is just:您还可以保留 resultDiv 的错误,它只是:

$("#resultDiv").hide().html(data.errorMsg)...

For the php side:对于 php 端:

if(!$row) {
  echo '{loggedIn:false,errorMsg:"<div class=\"alert alert-danger\" style=\"margin-top:25px; margin-bottom: 0px; text-align:center;\">Invalid <strong>username</strong> or <strong>password</strong>.</div>"}';
} else {

  $line = mysqli_fetch_assoc($query);

  $_SESSION['IP'] = $line["IP"];
  $_SESSION['ID'] = $line["ID"];
  $_SESSION['username'] = $username;

  echo '{loggedIn:true,location:"choose.php"}';

}

I hope this makes sense to you.我希望这对你有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM