js获取url查询字符串参数
阅读原文时间:2023年07月08日阅读:3

最近看js高级程序设计

对其中查询字符串参数的获得重新写了,当传递一个完整的URL的时候对查询字符串的提取

function getQueryArgs(){
var qs = (location.search.length > 0 ? location.search.substr(1) : ''),
//保存每一项
args = {},
//得到每一项
items = qs.length ? qs.split('&') : [],
item = null,
name = null,
value = null,
i = 0,
len = items.length;

    for(i = 0;i<len ;i++){  
        item = items\[i\].split('='),  
        name = decodeURIComponent(item\[0\])  
        value = decodeURIComponent(item\[1\])  
        if(name.length){  
            args\[name\] = value;  
        }  
    }  
    return args;  

}
getQueryArgs()

function getQueryArgs(url){
var qs = (url.length > 0 ? url.substring(url.indexOf('?')).substr(1) : ''),
//保存每一项
args = {},
//得到每一项
items = qs.length ? qs.split('&') : [],
item = null,
name = null,
value = null,
i = 0,
len = items.length;

    for(i = 0;i<len ;i++){  
        item = items\[i\].split('='),  
        name = decodeURIComponent(item\[0\])  
        value = decodeURIComponent(item\[1\])  
        if(name.length){  
            args\[name\] = value;  
        }  
    }  
    return args;  

}