【问题标题】:Is this the correct way to redirect?这是重定向的正确方法吗?
【发布时间】:2011-07-20 16:50:40
【问题描述】:

为了回应this question,我写了这个函数(嗯,我在那个答案中做得更详细一点):

function redirectto(url) {
    window.location.href = url; // first try it the easy way

    // we're going to do it the hard way - create a temporary form and submit it
    var tmpform = document.createElement("form");
    tmpform.method = "GET";

    // add data, use hidden fields for querystrings
    if (url.indexOf("?") == -1) {
        tmpform.action = url;
    } else {
        var urlparts = url.split("?", 2);
        tmpform.action = urlparts[0];

        var queryparts = urlparts[1].replace(/\+/g, " ").split(/[&;]/g);
        for (var i = 0; i < queryparts.length; i++) {
            var pair = queryparts[i].split("=");
            var key = pair[0];
            var value = pair.length > 1 ? pair[1] : "";

            var field;
            try { // sigh IE, can't you do ANYTHING right?
                field = document.createElement("<input type=\"hidden\" name=\"" + key + "\" value=\"" + value + "\">");
            } catch(err) {
                field = document.createElement("input");
                field.type = "hidden";
                field.name = key;
                field.value = value;
            }
            tmpform.appendChild(field);
        }
    }

    // add to page and submit
    document.body.appendChild(tmpform);
    tmpform.submit();
}

我写的答案得到了 3 票反对,所以我的问题是:这是正确的方法还是只是 window.location.href = url 足够?

【问题讨论】:

  • 为什么你认为window.location.href = url; 在 IE 中会失败?
  • 为什么要提交表单而不是在页面中注入&lt;a&gt; 并点击它。

标签: javascript redirect


【解决方案1】:

window.location.href = url一种重定向浏览器的有效方式。通常我不鼓励浏览器重定向,除非绝对必要。通过 JS 重定向的理由往往很少。

【讨论】:

  • 当然,按标准有效,但我的问题是它是否总是有效(瞪着 IE)。
  • @nightcracker 正如我上面评论的:为什么你认为window.location.href = url; 在 IE 中会失败?
  • OP 中链接的问题。
  • @nightcracker,如果您有任何理由相信它在浏览器中无法运行,请在地址栏中运行:javascript:window.location.href='http://www.google.com/';
【解决方案2】:

最好使用内置方法,因为它更高效,并且被大多数运行 javascript 的浏览器更广泛地支持,并且还需要更少的内存来加载和运行一个全新的函数。

window.location.href = url 是 zzzzBov 所说的重定向浏览器的有效方式

【讨论】:

    【解决方案3】:

    我觉得window.location.href = url 就够了。

    【讨论】:

      猜你喜欢
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多