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


当前回答

在我的工作经验中,JavaScript更好地重定向。

它取决于您想要如何更改位置. 如果您想在用户历史中登录您的网站,请使用 window.location.href='ur website';. 否则,如果您不登录历史,请使用 window.location.replace(“您的网站”);。

其他回答

下面是将代码转向另一个页面,时间为10秒。

<script>
    function Redirect()
    {
        window.location="http://www.adarshkr.com";
    }

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

你也可以这样做,点击一个按钮使用 location.assign:

<input type="button" value="Load new document" onclick="newPage()">
<script>
    function newPage() {
        window.location.assign("http://www.adarshkr.com")
    }
</script>

与 jQuery 合作:

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

因此,问题是如何创建一个重定向页面,而不是如何重定向到一个网站?

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

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

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

这就是你用JavaScript创建一个简单的重定向页面的方式。

我添加了 window.location.replace 在我的代码,因为我认为它适合一个重定向页面,但是,你必须知道,当使用 window.location.replace 和你得到重定向,当你按下后按钮在你的浏览器它不会回到重定向页面,它会回到页面之前,看看这个小演示事物。

例子:

因此,如果这符合您的需求,那么一切都应该顺利。 如果您想将重定向页面在浏览器历史中取代这个

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

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

使用 JavaScript:

方法1:

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

方法2:

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

使用 jQuery:

方法1: $(位置)

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

方法2:可重新使用的功能

jQuery.fn.redirectTo = function(url){
    window.location.href = url;
}

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

使用 jQuery 功能:

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

在你的代码中,你使用它如下:

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