美文网首页
获取URL参数(整理常用)

获取URL参数(整理常用)

作者: 一沭丶 | 来源:发表于2016-10-04 17:36 被阅读104次

1、获取某一个参数

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    var context = "";
    if (r != null)
         context = decodeURIComponent(r[2]);
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}
console.log(GetQueryString("name"));

2、获取所有的参数

function getQueryStriongArgs(){
        var qs = (location.search.length>0?location.search.substring(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;
    }
    var urlParams = getQueryStriongArgs();
    console.log(urlParams);

相关文章

网友评论

      本文标题:获取URL参数(整理常用)

      本文链接:https://www.haomeiwen.com/subject/uufsyttx.html