做页面跳转时经常需要保留当前的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¶m2=345');