[技巧篇]11.JavaScript原生态如何获取浏览器请求地址中的参数

var getAccessParams = 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(getAccessParams());

请求地址为:http://localhost:8001/shxt_web/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:8001/shxt_web/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"}

注意我这里callback是固定的值,可以更觉我的这里继续修改,根绝自己的要求自己搞定,感觉这个还是很好用的!

我依旧在坚持着程序员的道路,是否正确!

原文地址:https://www.cnblogs.com/pangxiansheng/p/4723144.html