这是重定向的正确方法吗?

时间:2011-07-20 16:50:40

标签: javascript redirect

在回复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个downvotes,所以我的问题是:这是正确的方法吗?或者仅仅是window.location.href = url吗?

3 个答案:

答案 0 :(得分:3)

window.location.href = url 重定向浏览器的有效方式。通常我会阻止浏览器重定向,除非绝对必要。通过JS重定向往往很少有的原因。

答案 1 :(得分:0)

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

而window.location.href = url是一种有效的重定向浏览器的方式,因为zzzzBov说

答案 2 :(得分:0)

我认为window.location.href = url就足够了。

相关问题