做页面跳转时经常需要保留当前的querystring,在网上搜了代码,没找到需要的,就自己写了一个。这段代码通过将querystring进行拆解,将新旧两段querystring进行合并。

//querystring to obj
function getQueryStringObj(queryString){
	var a = queryString.split("?")[1].split("&");
	var obj = {};
	for(var i=0; i<a.length; i++){
		var I = a[i].split("=");
		obj[I[0]] = I[1];
	}
	return obj;
}

function redirect(url,queryString){
	if(location.search == ""){
		window.location.href = url + queryString;
		return ;
	}
	if(queryString == ""){
		window.location.href = url + location.search;
		return ;
	}
	
	var currentQueryStringObj = getQueryStringObj(location.search);
	var newQueryStringObj = getQueryStringObj(queryString);
	for(var index in newQueryStringObj){
		currentQueryStringObj[index] = newQueryStringObj[index];
	}
	
	var newQueryString = "";
	for(var index in currentQueryStringObj){
		newQueryString += "&"+index+"="+currentQueryStringObj[index];
	}
	newQueryString = newQueryString.replace("&","?");
	window.location.href=url+newQueryString;
}

使用方法:

redirect('demo.php','?param=123&param2=345');

 

By charlie

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注