我如何将用户从一个页面转向另一个页面,使用jQuery或纯粹的JavaScript?


当前回答

如果你正在尝试生成包数据,有几个选项,你如何做到这一点,你可以生成单独的链接,每个页面你想能够直接到。

<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...

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

如果您希望通过 AJAX 更改已支付的数据,这就是 jQuery 会进入的地方. 您所做的就是将一个点击处理器添加到相应不同页面的每个 anchor 标签. 这个点击处理器会引用一些 jQuery 代码,并通过 AJAX 获取下一个页面并更新新数据的表。

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

其他回答

您可以在 jQuery 中以以下方式重定向:

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

在JavaScript和jQuery中,我们可以使用以下代码将一页转向另一页:

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

标准“瓦尼拉”JavaScript如何重新引导页面

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

location.href = 'newPage.html';


以下部分适用于使用 HTTP_REFERER 作为许多安全措施之一(尽管这不是一个很好的保护措施)。如果您使用 Internet Explorer 8 或更低,这些变量在使用任何形式的 JavaScript 页面重定向(location.href 等)时会失去。

下面我们将实施一个替代 IE8 和更低,以免失去 HTTP_REFERER. 否则,你几乎总是可以简单地使用 window.location.href。

对 HTTP_REFERER 进行测试(URL 粘贴、会话等)可以帮助您知道请求是否合法(注:在评论中提到 drop 的链接中,还有一些方法可以工作周围 / 扫描这些引用器)


简单的跨浏览器测试解决方案(下载到 window.location.href for Internet Explorer 9+ 和所有其他浏览器)

使用:重定向(“anotherpage.aspx”);

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; 
    }
}
<script type="text/javascript">
    if(window.location.href === "http://stackoverflow.com") {      
         window.location.replace("https://www.google.co.in/");
       }
</script>

您可以使用 window.location 设置。

例子:

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

此分類上一篇: 我如何轉向另一個網站?