javascript - 如何在纯 Javascript 中的 PHP AJAX 调用中使用 header 重定向?

标签 javascript php ajax

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

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

Javascript:

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;
                }
            } 

    }

关于javascript - 如何在纯 Javascript 中的 PHP AJAX 调用中使用 header 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44948894/

相关文章:

javascript - 使用 jQuery 获取表格内的文本框值

php - 每个查询不同的背景图像

php - laravel morphToMany 在数据透视表中有附加字段

php - jQuery ajax 调用 php 给出 404 not found : what am I missing?

javascript - 如果我在创建客户端后没有立即连接,则使用 sockjs-client 和 stompjs 的 WebSocket 无法连接

javascript - 运行网站上显示的计数器

javascript - 为什么ajax调用缓存表单数据?

javascript - 使用 AJAX 从 javascript 调用 Perl 脚本

javascript - Angular JS 在 ng-repeat 列表中使用模态

javascript - 从 AJAX 命令返回 JSON 格式的响应