繁体   English   中英

如何在纯 Javascript 中的 PHP AJAX 调用中使用标头重定向?

[英]How to use header redirect in PHP AJAX Call In Pure Javascript?

我正在创建一个登录表单,我需要将用户重定向到他/她的个人资料页面。 我正在使用 AJAX 请求,因此标头重定向根本不起作用。 它只是停留在主页上。

那么如何在纯 javascript PHP ajax 调用中将用户重定向到另一个页面呢? 请用纯 javascript 给出答案。 我根本不喜欢使用 jQuery!

Java脚本:

function ajaxCall(){
    var xhttp;

    if(window.XMLHttpRequest){
        xhttp = new XMLHttpRequest();
    }

    xhttp.onreadystatechange = function(){
        if(this.readyState === 4 && this.status === 200){
            document.getElementById('error').innerHTML = this.responseText;
        }
    };

    var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
    xhttp.open('POST', 'login.php', true);
    xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
    xhttp.send(parameters);
}

登录.php(PHP)

<?php
if(isset($_POST['email']) && isset($_POST['password'])){
    $ema = $_POST['email'];
    $pass = $_POST['password'];

    if(!empty($ema) && !empty($pass)){
        if($ema === 'Bill' && $pass === 'Cool'){
            header('Location: https://www.google.com');
        }
    }
}

进行ajax调用。

<?php
header('Content-Type: application/json');
echo json_encode(['location'=>'/user/profile/']);
exit;
?>

ajax 响应将返回类似

{'location':'/user/profile/'}

在您的 ajax 成功 javascript 函数中

 xhr.onreadystatechange = function () {
            if (xhr.status >= 200 && xhr.status <= 299)
            {
                var response = JSON.parse(xhr.responseText);
                if(response.location){
                  window.location.href = response.location;
                }
            } 

    }

我来到这里寻找 Ajax 解决方案,但 MontrealDevOne 的回答很有用。 如果其他人也对 ajax 方法感到好奇,请看这里:

$('body').on('submit', '#form_register', function (e) {
    var form = $(this);
    $.ajax({
          type: 'POST',
          url: 'form_submissions.php',
          data: form.serialize() + "&submit",
          dataType:"json",
              success: function (data) {
              if(data.location){
                window.location.href = data.location;
              }
          },
          error: function(data) {
              alert("Error!");
          }
      });
    e.preventDefault();
});

只是我的 2 美分,希望它有所帮助:)

如果有效,试试这个法案。

  window.location.replace("http://www.google.com");

暂无
暂无

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

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