js修改url
这篇文章主要介绍修改url地址的一些方法,包括:修改url重新加载,修改url但不重新加载。
修改url重新加载刷新页面
1、window.location.reload(),刷新页面,不重复提交页面。
2、window.location.href=window.location.href,刷新页面,不重复提交页面。
3、location.replace(location.href),刷新页面,不重复提交页面。
4、window.location.replace(location),重定向一个页面,也可以为当前页面。
5、window.opener.location.reload(); 父页面刷新加载,即当一个页面open一个新页面后可以在子页面,reload父页面。
6、其他一些非常用的刷新方法:
history.go(0)
location=location
document.execCommand('Refresh')
window.navigate(location)
document.URL=location.href7、html中meta标签
页面自动刷新:把如下代码加入区域中,其中20指每隔20秒刷新一次页面
<meta http-equiv="refresh" content="20">页面自动跳转:把如下代码加入区域中,其中20指隔20秒后跳转到 http://www.fly63.com 页面
<meta http-equiv="refresh" content="20;url="http://www.fly63.com">场景:使用js修改url地址参数并刷新页面
该方法可以修改url的参数。例如将www.fly63.com修改为www.fly63.com?name=123。代码如下:
function changeURLArg(url,arg,arg_val){
var pattern=arg+'=([^&]*)';
var replaceText=arg+'='+arg_val;
if(url.match(pattern)){
var tmp='/('+ arg+'=)([^&]*)/gi';
tmp=url.replace(eval(tmp),replaceText);
return tmp;
}else{
if(url.match('[\?]')){
return url+'&'+replaceText;
}else{
return url+'?'+replaceText;
}
}
}使用:
window.location.href = changeURLArg(window.location.href,'name',123)修改url但不重新加载
如果修改url但不重新加载,可以使用html5后引入的History.pushState(),History.replaceState()。pushState方法往历史记录中添加新记录,replaceState方法修改当前历史记录。
使用到的api
history.state当前URL下对应的状态信息。如果当前URL不是通过pushState或者replaceState产生的,那么history.state是null。
history.pushState(state, title, url)将当前URL和history.state加入到history中,并用新的state和URL替换当前。不会造成页面刷新。
- state:与要跳转到的URL对应的状态信息。
- title: 新页面的标题,但是所有浏览器目前都忽略这个值,因此这里可以填null或者空字符串 。
- url:要跳转到的URL地址,不能跨域。
history.replaceState参数同pushState,区别于pushState会直接替换掉当前url,而不会在history中留下记录。
例子:
//如果当前url为http://www.fly63.com/nav
history.replaceState({},"","/tool");
//现在为http://www.fly63.com/tool场景:使用js修改url地址参数不刷新页面
同样使用上述方法changeURLArg。
var newurl=changeURLArg(window.location.href,'name',123)
window.history.replaceState({path: newurl}, '', newurl);本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!