mcya / JavaScriptExperience

👮 JavaScript Experience for web(JavaScript归类:简单入门+数组+经典循环+字符串+函数+Date日期+简单对象+BOM+DOM) +[ Issues(js实用技巧)]
29 stars 8 forks source link

获取URL参数 #34

Open mcya opened 6 years ago

mcya commented 6 years ago
var data = "http://localhost:8989/#/saleMgr/houseQuery?_k=1rcgps&sp=123&un=undefine"
var allParamsArr = data.split("?")[1].split("&"), returnObj = {};
for(var i =0; i<allParamsArr.length; i++) {
    returnObj[`${allParamsArr[i].split("=")[0]}`] = allParamsArr[i].split("=")[1]
}
console.log(allParamsArr, returnObj)

VM791:6 (3) ["_k=1rcgps", "sp=123", "un=undefine"] {_k: "1rcgps", sp: "123", un: "undefine"}
mcya commented 6 years ago

最新的

//封装的函数
function getUrlParams(objName) {
    var data = window.location.href;
    if(data.indexOf("?")<0) return undefined; //判断是否存在参数
    var allParamsArr = data.split("?")[1].split("&"), returnObj = {};
    if(allParamsArr.length==0) return undefined; //参数是否带惨,狗屁的有的人无聊带问号不带参数的
    for(var i =0; i<allParamsArr.length; i++) {
        returnObj[`${allParamsArr[i].split("=")[0]}`] = allParamsArr[i].split("=")[1]
    }
    return returnObj[`${objName}`]
}

//引用方式
// 假设地址是:"http://localhost:8989/#/saleMgr/houseQuery?_k=1rcgps&sp=123&un=undefine"
var a = getUrlParams('sp') //返回 "123" 字符串
var a = getUrlParams('un') //返回 "undefine" 字符串
var a = getUrlParams('unn') //不存在,即返回 undefine