js中如何获取浏览器请求地址中的参数呢?
js获取请求的query string
- var getPageParams = function(){
- var i,ilen,strs,keyName,keyValue,
- params={},
- path = window.location.pathname,
- url = window.location.href;
- if(url.indexOf("?")>-1){
- var index=url.indexOf("?");
- strs=url.substring(index+1);
- console.log(strs);
- strs=strs.split("&");
- ilen=strs.length;
- for(i=0;i<ilen;i++){
- var indexEqual=strs[i].indexOf('=');
- keyName=strs[i].substring(0,indexEqual);
- keyValue=strs[i].substring(indexEqual+1);
- if(keyName=="callback") keyValue=decodeURIComponent(keyValue);
- params[keyName]=keyValue;
- }
- }
- return params;
- };
- console.log(getPageParams());
请求地址为:http://localhost:63342/chanjet_web_js/chanjet/js/test_whuang.html?callback=http://www.weixin.com?id=123&app=weixin
时,运行结果:
Object {callback: "http://www.weixin.com?id=123", app: "weixin"}
http://localhost:63342/chanjet_web_js/chanjet/js/test_whuang.html?callback=http://www.weixin.com?id=123&app=weixin&returnurl=http://www.baidu.com
运行结果:
Object {callback: "http://www.weixin.com?id=123", app: "weixin", returnurl: "http://www.baidu.com"}