使用 Javascript 重定向页面,如 PHP 的 Header->Location

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7558648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:43:37  来源:igfitidea点击:

Redirecting a page using Javascript, like PHP's Header->Location

javascriptredirect

提问by Keith Donegan

I have some code like so:

我有一些像这样的代码:

$('.entry a:first').click(function()
{
    <?php header("Location:" . "http://www.google.com"); ?>
});

I would like to know how I can achieve this using Javascript.

我想知道如何使用 Javascript 实现这一点。

回答by rlemon

You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)

您不能以这种方式混合 JS 和 PHP,PHP 在页面发送到浏览器之前呈现(即在 JS 运行之前

You can use window.location to change your current page.

您可以使用 window.location 来更改当前页面。

$('.entry a:first').click(function() {
    window.location = "http://google.ca";
});

回答by klaustopher

The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.

PHP 代码在服务器上执行,因此您的重定向甚至在浏览器看到 JavaScript 之前执行。

You need to do the redirect in JavaScript too

您也需要在 JavaScript 中进行重定向

$('.entry a:first').click(function()
{
    window.location.replace("http://www.google.com");
});

回答by Starx

You application of js and php in totally invalid.

你在js和php中的应用完全无效。

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

你必须明白一个事实,JS 运行在客户端,一旦页面加载它并不关心页面是 php 页面还是 jsp 或 asp。它执行 DOM 并且仅与它相关。

However you can do something like this

但是你可以做这样的事情

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

你看,当脚本加载时,上面的代码呈现成不同的形式,像这样

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

像上面一样,php和js融合有很多可能性,你正在做的不是其中之一。