MarkJane
4/12/2017 - 7:11 AM

JS-对象转URL参数,解析-URL-参数为-JS对象

JS-对象转URL参数,解析-URL-参数为-JS对象

/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 * 
 * return URL参数字符串
 */
var urlEncode = function (param, key, encode) {
  if(param==null) return '';
  var paramStr = '';
  var t = typeof (param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
};


var obj={name:'tom','class':{className:'class1'},classMates:[{name:'lily'}]};
console.log(urlEncode(obj));
//output: &name=tom&class.className=class1&classMates[0].name=lily
console.log(urlEncode(obj,'stu'));
//output: &stu.name=tom&stu.class.className=class1&stu.classMates[0].name=lily


//解析 URL 参数为 JS对象
function GetRequest() { 
    var url = location.search; //获取url中"?"符后的字串 
    var theRequest = new Object(); 
    if (url.indexOf("?") != -1) { 
        var str = url.substr(1); 
        strs = str.split("&"); 
        for(var i = 0; i < strs.length; i ++) { 
            theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); 
        } 
    }
    return theRequest;
}