javascript - 使用 header 和 javascript 代码重定向

标签 javascript php html

我用 PHP 创建了一个重定向页面,每当有人访问该页面时,它都会在浏览器中添加一个 cookie 并将用户重定向到其他页面:例如:google.com

为此,我使用了 javascript 进行重定向,但问题是当我提取网址时,它不显示 google.com。在提取过程中,它显示同一页面的信息,然后我使用 php header() 进行重定向,它会显示 google.com 信息。

现在我需要帮助才能使此代码与 cookie 和 header 一起使用。

代码:

<?php
header("location: https://www.google.com");
echo '<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <title>Redirecting...</title>
        <script type="text/javascript">
        function createCookie(name,value,days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            }
            else var expires = "";
            document.cookie = name+"="+value+expires+"; path=/";
        }
        createCookie("karachi","testing",100);
        </script>
    </head>
    <body>

    </body>
</html>';
?>

最佳答案

而不是在 JavaScript 上设置它。为什么不使用 PHP。

$date_of_expiry = time() + (86400 * 30); // 30 days
if(setcookie('karachi', 'testing', $date_of_expiry)) {
    sleep(3); // sleep 3 seconds
    header('Location: http://www.google.com/'); 
}

或者替代方案:

$date_of_expiry = time() + (86400 * 30); // 30 days
if(setcookie('karachi', 'testing', $date_of_expiry)) {
    echo '<h1>Redirecting.. Please wait.</h1>';
    echo '<meta http-equiv="refresh" content="3;url=http://www.google.com">';
}

在 JavaScript 上:

echo '<h1>Redirecting.. Please wait.</h1>';
// echo 'logic javascript';
echo '
<script>
setTimeout(function(){
    window.location.href = "http://www.google.com"
}, 3000);
</script>
';

关于javascript - 使用 header 和 javascript 代码重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24857516/

相关文章:

javascript - 标记(Markdown)+美人鱼(流程图和图表)

javascript - 如何在 angular.bootstrap() 之后设置 $rootScope 的值

php - 独立表单提交按钮

javascript - 无法通过 JQuery 访问选择框

jquery - 如何用mysql实现无限滚动?

javascript - 使用 HTML 运行 JSHint 并出现错误

javascript - 使用 ajax 和 PHP 裁剪后将图像保存到 MySQL

html - 当 ng-view 内容大于窗口高度时出现边框问题

javascript - 更改所选项目的文本以包括其父 optgroup

javascript - 从模态提交表单数据,模态不会关闭