解析浏览器地址json参数,及乱码问题

解析浏览器地址json参数

先看效果

获取浏览器地址url

let sHref = window.location.href  //浏览器整段地址

封装,解析url里面的字段,包含json格式

 // 获取url参数
                getWindonHref() {
                //获取浏览器url
                //列子file:///C:/Users/%E6%B8%A9%E8%BF%90%E6%B0%91/Desktop/h5/barlist/barlist.html?bar_list=[{%22id%22:%221%22,%22bar_name%22:%22%E6%B5%8B%E8%AF%95%E9%85%92%E5%90%A7%22,%22telephone%22:%2218072720735%22},{%22id%22:%222%22,%22bar_name%22:%22%E6%B5%8B%E8%AF%95%E9%85%92%E5%90%A72%22,%22telephone%22:%2218072720734%22}]
                    let sHref = window.location.href
                    //解码地址上的参数(会出现乱码情况需解析)
                    sHref = decodeURI(sHref)
                    // let sHref=`http://wxtoken.56good.net/h5view/form.php?type=1&json:[{name:'1',age:'2'},{name:'1',age:'2'}]`;
                    var args = sHref.split('?');//从中间的?隔开存成数组
                    if (args[0] === sHref) {
                        return '';//?后面没有参数直接返回
                    }
                    var hrefarr = args[1].split('#')[0].split('&');//截取?和#之间的url,再根据&隔开每个参数存成数组待处理
                    var obj = {};
                    for (var i = 0; i < hrefarr.length; i++) {
                        hrefarr[i] = hrefarr[i].split('=');
                        obj[hrefarr[i][0]] = hrefarr[i][1];
                    }
                    return obj;
                },

如果是单页(created),项目的话(onLoad)

created() {
//截取想要的字段(bar_list)
 let bar_list = this.getWindonHref().bar_list
 //[{"name":1},{}]  正常数组格式
}

你可能感兴趣的:(json,javascript,前端)