关于javascript:如何重定向到另一个网页?

How do I redirect to another webpage?

如何使用jquery或纯javascript将用户从一个页面重定向到另一个页面?


一个不是简单地使用jquery重定向

jquery不是必需的,window.location.replace(...)最好模拟HTTP重定向。

window.location.replace(...)比使用window.location.href要好,因为replace()在会话历史中不保留原始页,这意味着用户不会陷入无休止的后退按钮失败。

If you want to simulate someone clicking on a link, use
location.href

If you want to simulate an HTTP redirect, use location.replace

例如:

1
2
3
4
5
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href="http://stackoverflow.com";


WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.

1
$(location).attr('href', 'http://stackoverflow.com')


Standard"vanilla" JavaScript way to redirect a page:

window.location.href = 'newPage.html';

如果您在这里是因为重定向时丢失了HTTP引用,请继续阅读:

下面的部分是针对那些使用HTTP_REFERER作为许多安全措施之一的人(尽管它不是很好的保护措施)。如果您使用的是Internet Explorer 8或更低版本,那么在使用任何形式的javascript页面重定向(location.href等)时,这些变量都会丢失。

Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise you can almost always simply use window.location.href.

针对HTTP_REFERER的测试(URL粘贴、会话等)有助于判断请求是否合法。(注:正如Droop在评论中的链接所指出的,也有办法绕过/欺骗这些引用者)

简单的跨浏览器测试解决方案(对于Internet Explorer 9+和所有其他浏览器,返回window.location.href)

用法:redirect('anotherpage.aspx');

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function redirect (url) {
    var ua        = navigator.userAgent.toLowerCase(),
        isIE      = ua.indexOf('msie') !== -1,
        version   = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

    // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else {
        window.location.href = url;
    }
}


有很多方法可以做到这一点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'

// window.history
window.history.back()
window.history.go(-1)

// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')


// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';

// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')


这适用于每个浏览器:

1
window.location.href = 'your_url';


如果你对你想做的事情更具描述性,那会有所帮助。如果您正在尝试生成分页数据,那么在如何执行此操作中有一些选项。您可以为希望直接访问的每个页面生成单独的链接。

1
2
3
4
1
2
<span class='pager-link current-page'>3
...

注意,示例中的当前页面在代码和CSS中的处理方式不同。

如果您希望通过Ajax更改分页数据,jQuery就会出现在这里。您将要做的是向对应于不同页面的每个锚标记添加一个单击处理程序。这个点击处理程序将调用一些jquery代码,通过Ajax来获取下一页,并用新数据更新表。下面的示例假设您有一个返回新页面数据的Web服务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(document).ready( function() {
    $('a.pager-link').click( function() {
        var page = $(this).attr('href').split(/\?/)[1];
        $.ajax({
            type: 'POST',
            url: '/path-to-service',
            data: page,
            success: function(content) {
               $('#myTable').html(content);  // replace
            }
        });
        return false; // to stop link
    });
});

我也认为location.replace(URL)是最好的方法,但是如果你想通知搜索引擎你的重定向(他们不分析javascript代码来查看重定向),你应该在你的网站上添加rel="canonical"元标记。

添加一个包含HTML刷新元标记的noscript部分也是一个很好的解决方案。我建议您使用这个javascript重定向工具来创建重定向。它还支持Internet Explorer来传递HTTP引用。

没有延迟的示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!-- Place this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
    <meta http-equiv="refresh" content="0;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;<![endif]-->
<script type="text/javascript">
    var url ="https://yourdomain.com/";
    if(typeof IE_fix !="undefined") // IE8 and lower fix to pass the http referer
    {
        document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
        var referLink = document.createElement("a");
        referLink.href = url;
        document.body.appendChild(referLink);
        referLink.click();
    }
    else { window.location.replace(url); } // All other browsers

<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

但是如果有人想要重定向回主页,那么他可以使用下面的代码片段。

1
window.location = window.location.host

如果您有三种不同的环境,如开发、分段和生产,这将很有帮助。

只需将这些词放在Chrome控制台或Firebug控制台中,就可以浏览此window或window.location对象。


javascript提供了许多方法来检索和更改浏览器地址栏中显示的当前URL。所有这些方法都使用location对象,它是window对象的一个属性。您可以创建一个具有当前URL的新位置对象,如下所示。

1
var currentLocation = window.location;

URL的基本结构

1
<protocol>//<hostname>:<port>/<pathname><search><hash>

enter image description here

  • 协议——指定用于访问Internet上资源的协议名。(HTTP(不带SSL)或HTTPS(带SSL))

  • host name—主机名指定拥有资源的主机。例如,www.stackoverflow.com。服务器使用主机名提供服务。

  • 端口——一个端口号,用于识别一个特定的进程,当Internet或其他网络消息到达服务器时,它将被转发到该进程。

  • 路径名——路径提供了Web客户机想要访问的主机内特定资源的信息。例如,stackoverflow.com/index.html。

  • 查询——一个查询字符串跟随路径组件,并提供一个信息字符串,资源可以将其用于某些目的(例如,作为搜索的参数或作为要处理的数据)。

  • hash——URL的锚定部分,包括哈希符号()。

  • 使用这些位置对象属性,您可以访问所有这些URL组件

  • hash-设置或返回URL的锚定部分。
  • 宿主集或者返回URL的主机名和端口。
  • hostname-设置或返回URL的主机名。
  • href-设置或返回整个网址。
  • 路径名-设置或返回URL的路径名。
  • 端口-设置或返回服务器用于URL的端口号。
  • 协议-设置或返回URL的协议。
  • 搜索集或返回URL的查询部分
  • 现在,如果您想更改页面或将用户重定向到其他页面,您可以使用这样的location对象的href属性。

    您可以使用location对象的href属性。

    1
    window.location.href="http://www.stackoverflow.com";

    定位对象也有这三种方法

  • assign()--加载新文档。
  • reload()--重新加载当前文档。
  • replace()--用新文档替换当前文档
  • 您还可以使用assign()和replace方法重定向到其他类似的页面

    1
    2
    3
    location.assign("http://www.stackoverflow.com");

    location.replace("http://www.stackoverflow.com");

    assign()和replace()的区别是replace()方法和assign()方法的区别是replace()从文档历史记录中删除当前文档的URL,这意味着无法使用"返回"按钮导航回原始文档。因此,如果您想加载一个新的文档,并想给这个选项返回到原始文档,那么可以使用assign()方法。

    也可以使用jquery更改location对象href属性,如下所示

    1
    $(location).attr('href',url);

    因此,您可以将用户重定向到其他URL。


    应该可以使用window.location进行设置。

    例子:

    1
    window.location ="https://stackoverflow.com/";

    这是过去关于这个主题的帖子:

    How do I redirect to another webpage?


    基本上,jquery只是一个javascript框架,在这种情况下,对于执行重定向等操作,您可以使用纯javascript,因此在这种情况下,您可以使用普通javascript有3个选项:

    1)使用位置替换,这将替换页面的当前历史记录,意味着无法使用后退按钮返回原始页面。

    1
    window.location.replace("http://stackoverflow.com");

    2)使用位置分配,这将为您保留历史记录,使用后退按钮,您可以返回原始页面:

    1
    window.location.assign("http://stackoverflow.com");

    3)我建议使用上述方法之一,但这可能是使用纯javascript的第三个选项:

    1
    window.location.href="http://stackoverflow.com";

    您也可以在jquery中编写一个函数来处理它,但不推荐使用它,因为它只是一行纯javascript函数,如果您已经在窗口范围内,也可以使用上面所有没有窗口的函数,例如window.location.replace("http://stackoverflow.com");可以是location.replace("http://stackoverflow.com");

    我也在下面的图片中展示了它们:

    location.replace location.assign


    在我开始之前,jquery是一个用于DOM操作的JavaScript库。所以您不应该使用jquery进行页面重定向。

    jquery.com的报价:

    While jQuery might run without major issues in older browser versions,
    we do not actively test jQuery in them and generally do not fix bugs
    that may appear in them.

    它是在这里发现的:https://jquery.com/browser-support(浏览器支持)/

    所以jquery并不是一个向后兼容的完整解决方案。

    The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.

    此页面将在3000毫秒后重定向到Google

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <!DOCTYPE html>
    <html>
        <head>
            <title>example</title>
        </head>
        <body>
            <p>
    You will be redirected to google shortly.
    </p>
           
                setTimeout(function(){
                    window.location.href="http://www.google.com"; // The URL that will be redirected too.
                }, 3000); // The bigger the number the longer the delay.
           
        </body>
    </html>

    不同的选项如下:

    1
    2
    3
    4
    5
    6
    7
    8
    window.location.href="url"; // Simulates normal navigation to a new page
    window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
    window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL

    window.history.back(); // Simulates a back button click
    window.history.go(-1); // Simulates a back button click
    window.history.back(-1); // Simulates a back button click
    window.navigate("page.html"); // Same as window.location="url"

    使用replace时,"上一步"按钮不会返回重定向页,就好像它从未出现在历史记录中一样。如果您希望用户能够返回重定向页面,那么使用window.location.hrefwindow.location.assign。如果您确实使用了一个允许用户返回重定向页面的选项,请记住,当您进入重定向页面时,它将重新定向您。所以在为你的重定向选择选项时要考虑到这一点。在只有当用户执行某项操作时才重定向页面的情况下,将页面置于后退按钮历史记录中是可以的。但是,如果页面自动重定向,那么您应该使用replace,这样用户就可以使用back按钮而不必被迫返回重定向发送的页面。

    您还可以使用元数据运行页面重定向,如下所示。

    元刷新

    1
    <meta http-equiv="refresh" content="0;url=http://evil.com/" />

    元定位

    1
    <meta http-equiv="location" content="URL=http://evil.com" />

    基地劫持

    1
    <base href="http://evil.com/" />

    在这个页面上可以找到更多的方法来将您不信任的客户机重定向到他们不希望访问的页面(其中没有一个方法依赖于jquery):

    https://code.google.com/p/html5security/wiki/RedirectionMethods

    我还想指出,人们不喜欢被随机重定向。只有在绝对需要的时候才改变人们的方向。如果你开始随机重定向用户,他们就不会再去你的网站了。

    下一部分是假设性的:

    You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.

    请查看有关重定向的谷歌网站管理员指南:https://support.google.com/webmasters/answer/2721217?hl=en&ref_主题=6001971

    这是一个有趣的小页面,让你从这个页面中脱颖而出。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <!DOCTYPE html>
    <html>
        <head>
            <title>Go Away</title>
        </head>
        <body>
            Go Away
           
                setTimeout(function(){
                    window.history.back();
                }, 3000);
           
        </body>
    </html>

    如果将这两个页面示例结合在一起,您将有一个重新路由的婴儿循环,它将确保您的用户永远不会再希望使用您的站点。


    1
    2
    var url = 'asdf.html';
    window.location.href = url;

    在没有jquery的情况下,可以这样做:

    1
    window.location ="http://yourdomain.com";

    如果您只需要jquery,那么您可以这样做:

    1
    $jq(window).attr("location","http://yourdomain.com");


    这适用于jquery:

    1
    $(window).attr("location","http://google.fr");

    #使用jquery/javascript重定向HTML页面

    尝试以下示例代码:

    1
    2
    3
    4
    5
    6
    7
    8
    function YourJavaScriptFunction()
    {
        var i = $('#login').val();
        if (i == 'login')
            window.location ="login.php";
        else
            window.location ="Logout.php";
    }

    如果你想给出一个完整的网址作为window.location ="www.google.co.in";


    您需要将此行放入代码中:

    1
    $(location).attr("href","http://stackoverflow.com");

    如果没有jquery,请使用javascript:

    1
    2
    window.location.replace("http://stackoverflow.com");
    window.location.href("http://stackoverflow.com");


    所以,问题是如何创建重定向页面,而不是如何重定向到网站?

    您只需要为此使用JavaScript。下面是一些将创建动态重定向页面的小代码。

    1
    2
        var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
        if( url ) window.location.replace(url);

    假设你把这段代码放到你网站上的redirect/index.html文件中,你可以这样使用它。

    http://www.mywebsite.com/redirect?url=http://stackoverflow.com

    如果你转到那个链接,它会自动将你重定向到stackoverflow.com。

    Link to Documentation

    这就是如何用javascript创建一个简单的重定向页面

    编辑:

    还有一件事需要注意。我在我的代码中添加了window.location.replace,因为我认为它适合重定向页面,但是,您必须知道,当使用window.location.replace并重定向时,当您在浏览器中按下后退按钮时,它将不会返回重定向页面,它将返回到之前的页面,请看这个小演示。

    例子:

    The process: store home => redirect page to google => google

    When at google: google => back button in browser => store home

    所以,如果这符合你的需要,那么一切都应该是好的。如果要在浏览器历史记录中包含重定向页,请替换此

    1
    if( url ) window.location.replace(url);

    具有

    1
    if( url ) window.location.href = url;

    在您的点击功能上,只需添加:

    1
    2
    3
    4
    window.location.href="The URL where you want to redirect";
    $('#id').click(function(){
        window.location.href="http://www.google.com";
    });

    *****最初的问题是-"如何使用jquery重定向",因此答案实现jquery>>免费使用案例*****

    只需重定向到带有javascript的页面:

    1
      window.location.href="/contact/";

    或者如果您需要延迟:

    1
    2
    3
    setTimeout(function () {
      window.location.href="/contact/";
    }, 2000);   // Time in milliseconds

    jquery允许您轻松地从网页中选择元素。您可以在页面上找到您想要的任何内容,然后使用jquery添加特殊效果、对用户操作作出反应,或者在所选元素内部或外部显示和隐藏内容。所有这些任务都从知道如何选择元素或事件开始。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
         $('a,img').on('click',function(e){
             e.preventDefault();
             $(this).animate({
                 opacity: 0 //Put some CSS animation here
             }, 500);
             setTimeout(function(){
               // OK, finished jQuery staff, let's go redirect
               window.location.href="/contact/";
             },500);
         });

    假设有人写了一个脚本/插件,它是10000行代码?!好吧,使用jquery,只需一两行就可以连接到这段代码。


    试试这个:

    1
    location.assign("http://www.google.com");

    示例的代码段。


    不需要jquery。您可以这样做:

    1
    window.open("URL","_self","","")

    就这么简单!

    启动HTTP请求的最佳方法是使用document.loacation.href.replace('URL')


    先写好。您希望在应用程序中导航另一个链接,该链接来自应用程序中的另一个链接。代码如下:

    1
    window.location.href="http://www.google.com";

    如果你想在你的应用程序中导航页面,我也有代码,如果你想的话。


    在jquery中可以这样重定向:

    1
    $(location).attr('href', 'http://yourPage.com/');


    在javascript和jquery中,我们可以使用以下代码将一个页面重定向到另一个页面:

    1
    2
    window.location.href="http://google.com";
    window.location.replace("page1.html");

    Javascript:

    1
    2
    3
    window.location.href='www.your_url.com';
    window.top.location.href='www.your_url.com';
    window.location.replace('www.your_url.com');

    jQuery:

    1
    2
    3
    var url='www.your_url.com';
    $(location).attr('href',url);
    $(location).prop('href',url);//instead of location you can use window


    ecmascript 6+jquery,85字节

    1
    $({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")

    请不要杀我,这是个笑话。这是个笑话。这是个笑话。

    这确实"提供了问题的答案",从某种意义上说,它要求"使用jquery"的解决方案,在这种情况下,需要以某种方式强制它进入方程。

    费里比格显然需要解释这个笑话(我仍然在开玩笑,我相信在审查表上有有限的选择),所以不用再多说了:

    其他的答案是不必要地在locationwindow对象上使用jquery的attr()

    这个答案也滥用了它,但更荒谬的是。它不使用它来设置位置,而是使用attr()来检索设置位置的函数。

    函数命名为jQueryCode,即使没有jquery,调用函数somethingCode也很可怕,尤其是当某个东西甚至不是语言时。

    "85字节"是对code golf的引用。打高尔夫球显然不是你应该在代码高尔夫之外做的事情,而且这个答案显然不是打高尔夫球。

    基本上,畏缩。


    这里是一个延时重定向。您可以将延迟时间设置为所需的时间:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <!doctype html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <title>Your Document Title</title>
        <script type="text/javascript">
            function delayer(delay) {
                onLoad = setTimeout('window.location.href="http://www.google.com/"', delay);
            }
       
    </head>

    <body>
       
            delayer(8000)
       
        You will be redirected in 8 seconds!
    </body>

    </html>


    我只需要用另一个更新的jquery方法来更新这个荒谬的地方:

    1
    2
    var url = 'http://www.fiftywaystoleaveyourlocation.com';
    $(location).prop('href', url);

    有三种主要方法可以做到这一点,

    1
    2
    window.location.href='blaah.com';
    window.location.assign('blaah.com');

    还有…

    1
    window.location.replace('blaah.com');

    最后一个是最好的,对于传统的重定向,因为它不会保存您在搜索历史记录中被重定向之前所访问的页面。但是,如果您只想用javascript打开一个选项卡,可以使用上面的任何一个。1

    编辑:可以选择window前缀。


    在php、html或jquery部分后面编写以下代码。如果在php或html部分的中间,则使用标记。

    1
    location.href="http://google.com"

    用于重定向页面或URL的jquery代码

    First Way

    这是用于重定向页面的jquery代码。因为,我已经将此代码放到了$(document.ready()函数上,它将在页面加载后立即执行。

    1
    2
    var url ="http://stackoverflow.com";
    $(location).attr('href',url);

    甚至可以将URL直接传递给attr()方法,而不是使用变量。

    Second Way

    1
     window.location.href="http://stackoverflow.com";

    您也可以这样编码(内部相同):

    1
    window.location="http://stackoverflow.com";

    如果您对window.location和window.location.href之间的区别感到好奇,那么可以看到后者显式地设置href属性,而前者隐式地设置。因为window.location返回一个对象,默认情况下,该对象设置了其.href属性。

    Third Way

    还有另一种使用javascript重定向页面的方法,即window.location对象的replace()方法。您可以将一个新的URL传递给replace()方法,它将模拟HTTP重定向。顺便说一句,请记住,window.location.replace()方法不会将原始页面放在会话历史记录中,这可能会影响后退按钮的行为。有时候,这是你想要的,所以要小心使用。

    1
    2
    // Doesn't put originating page in history
    window.location.replace("http://stackoverflow.com");

    Fourth Way

    类似于attr()方法(在jquery 1.6引入之后)

    1
    2
    var url ="http://stackoverflow.com";
    $(location).prop('href', url);


    在jquery中,使用$(location).attr('href', url)

    1
    2
    3
    4
    $(document).ready(function(){
        var url ="https://www.youtube.com/watch?v=JwMKRevYa_M";
        $(location).attr('href', url); // Using this
    });
    1
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

    在原始的javascript中,有很多方法可以实现这一点:

    1
    window.location.href="https://www.youtube.com/watch?v=JwMKRevYa_M";

    -显式设置Href属性。

    1
    window.location ="http://www.GameOfThrones.com";

    -是否隐式执行此操作,因为window.location返回一个对象,默认情况下该对象设置其.href属性。

    1
    window.location.replace("http://www.stackoverflow.com");

    -用新窗口替换当前窗口的位置。

    1
    self.location ="http://www.somewebsite.com";

    -设置当前窗口本身的位置。

    下面是一个在特定时间(3秒)后进行javascript重定向的示例:

    1
    2
    3
        setTimeout(function() {
            window.location.href="https://www.youtube.com/";
        }, 3000);


    使用javascript:方法1:

    1
    window.location.href="http://google.com";

    方法2:

    1
    window.location.replace("http://google.com");

    使用jQuery:方法1:$(位置)

    1
    $(location).attr('href', 'http://google.com');

    方法2:可重用函数

    1
    2
    3
    4
    5
    jQuery.fn.redirectTo = function(url){
        window.location.href = url;
    }

    jQuery(window).redirectTo("http://google.com");


    在javascript和jquery中,我们使用以下代码重定向页面:

    1
    2
    window.location.href="http://google.com";
    window.location.replace("page1.html");

    但您可以在jquery中创建一个函数来重定向页面:

    1
    2
    3
    4
    jQuery.fn.redirect=function(url)
    {
        window.location.href=url;
    }

    并调用此函数:

    1
    jQuery(window).redirect("http://stackoverflow.com/")


    使用jquery函数:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    $.extend({
      redirectPost: function(location, args) {
        var form = '';
        $.each(args, function(key, value) {
          form += '<input type="hidden" name="' + key + '" value="' + value + '">';
        });
        $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
      }
    });

    在代码中,您可以这样使用它:

    1
    $.redirectPost("addPhotos.php", {pimreference:  $("#pimreference").val(), tag: $("#tag").val()});

    仅在javascript中,您可以使用以下方法重定向到特定页面:

    1
    window.location.replace("http://www.test.com");

    1
    location.replace("http://www.test.com");

    1
    window.location.href="http://www.test.com";

    使用jQuery:

    1
    $(window).attr("location","http://www.test.com");

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <script type="text/javascript">
    var url ="https://yourdomain.com";

    // IE8 and lower fix
    if (navigator.userAgent.match(/MSIE\s(?!9.0)/))
    {
        var referLink = document.createElement("a");
        referLink.href = url;
        document.body.appendChild(referLink);
        referLink.click();
    }

    // All other browsers
    else { window.location.replace(url); }

    javascript非常广泛。如果你想跳到另一个页面,你有三个选项。

    1
    2
    3
    4
    5
     window.location.href='otherpage.com';
     window.location.assign('otherpage.com');
     //and...

     window.location.replace('otherpage.com');

    如果您需要的话,您可以使用这些页面中的任何一个。然而,这三种选择都局限于不同的情况。根据你的要求明智地选择。

    如果你对这个概念有更多的了解。你可以走得更远。

    1
    2
    3
    4
    5
    window.location.href; returns the href (URL) of the current page
    window.location.hostname; returns the domain name of the web host
    window.location.pathname; returns the path and filename of the current page
    window.location.protocol; returns the web protocol used (http: or https:)
    window.location.assign; loads a new document

    下面是用于重定向到其他某个超时为10秒的页面的代码。

    1
    2
    3
    4
    5
    6
    7
        function Redirect()
        {
            window.location="http://www.adarshkr.com";
        }

        document.write("You will be redirected to a new page in 10 seconds.");
        setTimeout('Redirect()', 10000);

    您也可以这样做,使用location.assign单击按钮:

    1
    2
    3
    4
    5
    <input type="button" value="Load new document" onclick="newPage()">

        function newPage() {
            window.location.assign("http://www.adarshkr.com")
        }


    您可以像在下面的代码中那样使用它,其中getRequestToForwardPage是请求映射(url)。您也可以使用您的URL。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    function savePopUp(){
        $.blockUI();
        $.ajax({
            url:"saveGuestHouse?roomType="+$("#roomType").val(),
            data: $("#popForm").serialize(),
            dataType:"json",
            error: (function() {
                alert("Server Error");
                $.unblockUI();
        }),
        success: function(map) {
            $("#layer1").hide();
            $.unblockUI();
            window.location ="getRequestToForwardPage";
        }
    });

    这与应用程序的上下文相同。

    如果您只想使用jquery特定的代码,那么以下代码可能会有所帮助:

    1
    2
    3
     $(location).attr('href',"http://www.google.com");
     $jq(window).attr("location","http://www.google.com");
     $(location).prop('href',"http://www.google.com");

    1
    2
    3
    4
    <script type="text/javascript">
        if(window.location.href ==="http://stackoverflow.com") {      
             window.location.replace("https://www.google.co.in/");
           }


    你可以使用:

    1
    window.location.replace("http://www.example.com/");

    replace()方法不会在会话历史记录中保存原始页,因此用户无法使用后退按钮返回并重新定向。注意:在这种情况下,浏览器后退按钮将被停用。

    但是,如果您希望获得与单击链接相同的效果,则应执行以下操作:

    1
    window.location.href="http://www.example.com/";

    在这种情况下,浏览器后退按钮将处于活动状态。


    您可以使用以下方法重定向页面:

  • 在head-中使用meta标记。注意,content="0;…用于在需要多少秒后重定向页面

  • 使用javascript:window.location.href="http://your-page-url.com";

  • 使用jquery:$(location).attr('href', 'http://yourPage.com/');


  • 用途:

    1
    2
    3
    function redirect(a) {
        location = a
    }

    打电话给:redirect([url]);

    location之后不需要href,这是隐含的。


    您可以在脚本部分中为按钮单击事件编写url.action,如下所示。

    1
    2
    3
    function onclick() {
            location.href = '@Url.Action("Index","Home")';
        }


    单页应用程序,在同一应用程序路由内

    1
    window.location.pathname = '/stack';

    JavaScript:

    1
    2
    location.href="http://stack.com";
    window.location ="http://stack.com";

    jQuery:

    1
    2
    $(location).attr('href',"http://www.stack.com");
    $(window).attr('location',"http://www.stack.com");

    角度4

    1
    2
    3
    4
    5
    6
    import { Router } from '@angular/router';
    export class NavtabComponent{
        constructor(private router: Router) {
        }
        this.router.navigate(['bookings/taxi']);
    }

    我只是添加了另一种方式:

    要将站点的任何特定页面/链接重定向到其他页面,只需添加以下代码行:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
        if(window.location.href == 'old_url')
        {
            window.location.href="new_url";
        }

        // Another URL redirect
        if(window.location.href == 'old_url2')
        {
            window.location.href="new_url2";
        }

    对于现实生活中的例子,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
        if(window.location.href == 'https://old-site.com')
        {
            window.location.href="https://new-site.com";
        }

        // Another URL redirect
        if(window.location.href == 'https://old-site.com/simple-post.html')
        {
            window.location.href="https://new-site.com/simple-post.html";
        }

    通过使用这个简单的代码,您可以重定向整个站点或任何单个页面。


    这很容易实现。你可以使用:

    1
    window.location.href="http://www.example.com/";

    这将记住上一页的历史记录。所以你可以通过点击浏览器的后退按钮返回。

    或:

    1
    window.location.replace("http://www.example.com/");

    此方法不记得上一页的历史记录。在这种情况下,"后退"按钮将被禁用。


    如果你喜欢使用纯javascript,我意识到使用document.location.href="https://example.com"window.location.href="https://example.com"会导致火狐的兼容性问题。而是尝试使用:

    1
    2
    location.href="https://example.com";
    location.replace("http://example.com");

    在我的情况下解决了这个问题。祝你好运!


  • location.assign()位置:

    通过向路由路径传递路径来分配路由路径。即使在分配了路径之后,assign也会给您一个历史记录。

    用法:应将值传递给它。

    例如:location.assign("http://google.com")

    Enter image description here

  • 地点

    可以定义一条进入它的路径…一旦设置好它就会重定向到一个给定的路径,并且它会保持历史…

    用法:应将值赋给它。

    例如:location.href="http://google.com"

  • location.replace()位置:

    如果不想保留历史记录,它将有助于替换路径。一旦你替换了它的路径,它就不会给你一个历史。

    用法:值应传递给它。

    例如:location.replace("http://google.com")

    Enter image description here

  • assign()href是相似的,两者都可以保存历史。assign通过传递一个值来工作,href通过赋值来工作。

    您可以使用javascript本身来实现它,而无需使用jquery,

    1
    2
    window.location ="http://google.com"
    location.href="http://google.com"

    您可以使用下面的jquery实现类似的事情。就像上面一样,

    1
    2
    $(window).attr('location',"http://www.google.com");
    $(location).attr('href',"http://www.google.com");

    你很容易理解两者之间的区别…

    这是位置对象,

    Location API from chrome


    我已经使用了javascript的redirect()函数。它在工作。

    1
    2
    3
    4
    5
    6
    7
    8
    <script type="text/javascript">
        $(function () {
            //It's similar to HTTP redirect
            window.location.replace("http://www.Technomark.in");

            //It's similar to clicking on a link
            window.location.href="Http://www.Technomark.in";
        })


    如果你想在同一个应用程序中重定向到一个路由

    1
    window.location.pathname = '/examplepath'

    就是这样。


    使用location.replace()将重定向您,但不会保存上一页的历史记录。提交表单时最好使用此选项。但是如果你想保留你的历史,你必须使用location.href=//path

    实例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // form with steps
    document.getElementById('#next').onclick = function() {
       window.location.href='/step2' // iteration of steps;
    }

    // go to next step
    document.getElementById("#back').onclick = function() {
       window.history.back();
    }

    // finish
    document.getElementById("
    #finish').onclick = function() {
       window.location.href = '
    /success';
    }

    // on success page
    window.onload = function() {
        setTimeout(function() {
           window.location.replace('
    /home'); // i can't go back to success page by pressing the back button
        },3000);
    }

    一路从客户端进行重定向:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    <!DOCTYPE html>
    <html>
        <head>
            <title>JavaScript and jQuery example to redirect a page or URL </title>
        </head>
        <body>
           
                Redirecting to another page
           

            <script src="scripts/jquery-1.6.2.min.js">
           
                // JavaScript code to redirect a URL
                window.location.replace("http://stackoverflow.com");
                // window.location.replace('http://code.shouttoday.com');

                // Another way to redirect page using JavaScript

                // window.location.assign('http://code.shouttoday.com');
                // window.location.href = 'http://code.shouttoday.com';
                // document.location.href = '/relativePath';

                //jQuery code to redirect a page or URL
                $(document).ready(function(){
                    //var url ="http://code.shouttoday.com";
                    //$(location).attr('href',url);
                    // $(window).attr('location',url)
                    //$(location).prop('href', url)
                });
           
        </body>
    </html>


    使用jquery/javascript重定向用户

    通过使用jquery或javascript中的location对象,我们可以将用户重定向到另一个网页。

    在jQuery中

    将用户从一个页面重定向到另一个页面的代码是:

    1
    2
    var url = 'http://www.example.com';
    $(location).attr('href', url);

    在JavaScript中

    将用户从一个页面重定向到另一个页面的代码是:

    1
    2
    var url = 'http://www.example.com';
    window.location.href = url;

    1
    2
    var url = 'http://www.example.com';
    window.location = url;

    这就是我如何使用它。

    1
    2
    3
    4
    5
    6
       window.location.replace('yourPage.aspx');  
       // If you're on root and redirection page is also on the root

       window.location.replace(window.location.host + '/subDirectory/yourPage.aspx');

       // If you're in sub directory and redirection page is also in some other sub directory.


    根据我的工作经验,javascript更适合重定向。

    这取决于您想如何更改位置。如果您想在用户历史记录中登录您的网站,请使用window.location.href='ur website';。否则,要在不登录历史记录的情况下执行此操作,请使用window.location.replace("your website");