利用pushState开发无刷新页面修改url参数

因为想要实现 tab切换 添加参数和修改参数值,一开始的思路是:

 /* 
		    * url 目标url 
		    * arg 需要替换的参数名称 
		* arg_val 替换后的参数的值 
		* return url 参数替换后的url 
		*/ 
		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; 
				} 
			} 
			return url+'\n'+arg+'\n'+arg_val; 
		} 
location.href=location.href+"&paging="+tabtitliIndex;   //添加paging参数,
location.href=changeURLArg(location.href,'paging',tabtitliIndex);  //修改参数

的方法去添加和修改参数,发现页面是处于一直刷新的状态,不是我想要的效果。

后来发现有一种改变参数不刷新的方法:

使用到的API

history.state

当前URL下对应的状态信息。如果当前URL不是通过pushState或者replaceState产生的,那么history.state是null。

history.pushState(state, title, url)

将当前URL和history.state加入到history中,并用新的state和URL替换当前。不会造成页面刷新。

state:与要跳转到的URL对应的状态信息。

title:不知道干啥用,传空字符串就行了。

url:要跳转到的URL地址,不能跨域。

history.replaceState

用新的state和URL替换当前。不会造成页面刷新。

state:与要跳转到的URL对应的状态信息。

title:不知道干啥用,传空字符串就行了。

url:要跳转到的URL地址,不能跨域。

window.onpopstate

history.go和history.back(包括用户按浏览器历史前进后退按钮)触发,并且页面无刷的时候(由于使用pushState修改了history)会触发popstate事件,事件发生时浏览器会从history中取出URL和对应的state对象替换当前的URL和history.state。通过event.state也可以获取history.state。

支持性判断

if ('pushState' in history) {...}

我使用的是以下方法:

var state = {'paging':''};
var title = "";
var url = location.href;
history.pushState(state, title, url);
state = {'paging':tabtitliIndex};
url = changeURLArg(location.href,'paging',tabtitliIndex);
history.replaceState(state, title, url);

即可实现了无刷新页面进行参数修改;



再添加一条 获取url里边参数的方法:

function getQueryString(name) {   
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");   
	var r = window.location.search.substr(1).match(reg);   
	if (r != null) return unescape(r[2]);   
	return null;   
}
tabtitliIndex = getQueryString("paging");


猜你喜欢

转载自blog.csdn.net/dream0129/article/details/80431038