【发布时间】:2015-10-27 18:16:21
【问题描述】:
如何通过保留原始 URL 的 URL 参数来执行 Javascript 重定向 url?
例如
原网址:http://test.com?a=1&b=2
重定向到:http://sample.com?a=1&b=2
【问题讨论】:
标签: javascript jquery html redirect
如何通过保留原始 URL 的 URL 参数来执行 Javascript 重定向 url?
例如
原网址:http://test.com?a=1&b=2
重定向到:http://sample.com?a=1&b=2
【问题讨论】:
标签: javascript jquery html redirect
以下将获取当前 URL 查询字符串:
var query = window.location.search;
然后可以在重定向中使用:
window.location.replace('sample.com' + query);
更新
.replace() 方法将从浏览器历史记录中删除当前 URL。如果您想保留当前 URL,请使用 @igor 提到的 .assign()
【讨论】:
location.assign('sample.com' + location.search),如果重定向目标需要保存在浏览器历史记录中。
修改位置对象:
location.href = location.href.replace ( new RegExp("^" + "http://test.com"), "http://sample.com/" );
该语句替换加载当前文档的 url 的开头。来自新 url 的资源将自动加载。
您的示例网址不包含路径和片段部分(如http://test.com/the/path/compon.ent?a=1&b=2#a_fragment)。它们可以访问为
location.pathname // 'http://test.com/the/path/compon.ent'
location.hash // '#a_fragment'
请注意,这些 url 组件的出现建议按照@MattSizzle 在他的回答中概述的方式明确构成新的 url。
【讨论】: