如何在纯Javascript中的PHP AJAX调用中使用标头重定向? [英] How to use header redirect in PHP AJAX Call In Pure Javascript?

查看:51
本文介绍了如何在纯Javascript中的PHP AJAX调用中使用标头重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage.

So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!

JavaScript:

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

Login.php(PHP)

Login.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响应将返回类似

The ajax response will return something like

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

在您的ajax成功javascript函数中

In your ajax success javascript function

 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中的PHP AJAX调用中使用标头重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆