js 获取路径查询参数

317 阅读1分钟

需求:

以对象形式获取路径中的查询参数

http://localhost:8080/index?name=gx&type=sale

解决:

创建一个工具函数

/**
 * 获取路径上的查询参数
 * searchStr (window.location.search)
 */
function getQueryArgs(searchStr){
    var qs = (searchStr.length > 0 ? searchStr.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(window.location.search)

返回值

{
    name: "gx"
    type: "sale"
}

参考:www.cnblogs.com/qqfontofweb…