开发者

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

开发者 https://www.devze.com 2023-04-07 11:34 出处:网络
I have some code like so: $(\'.entry a:first\').click(function() { <?php header(\"Location:\" . \"ht开发者_如何学Pythontp://www.google.com\"); ?>

I have some code like so:

$('.entry a:first').click(function()
{
    <?php header("Location:" . "ht开发者_如何学Pythontp://www.google.com"); ?>
});

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


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)

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

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


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

You need to do the redirect in JavaScript too

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


You application of js and php in totally invalid.

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号