响应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
是一种 重定向浏览器的有效方式。通常我不鼓励浏览器重定向,除非绝对必要。通过 JS 重定向往往没有什么好的理由。
关于javascript - 这是重定向的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6765512/