在某些场景中我们需要使用 GET方式 ,并且需要拼出请求参数,比如window.open时,a标签的href等等.像这种拼接字符串的代码很容易发生错误,比如要将一个对象的所有属性和值拼接为URL的请求参数,我们可能需要这样:
var params = '';
params += 'key1='+obj.key1;
params += 'key2='+obj.key2;
params += 'key3='+obj.key3;
params += 'key4='+obj.key4;
...
不用说太多,痛苦啊,就像苦力,一点也体会不到程序员高大上的感觉.或许,我们可以这样
var params = urlEncode(obj);
既然这样,这是怎么实现的呢?先看一看网上一哥们基于jQuery的实现方案
var parseParam=function(param, key){
var paramStr="";
if(param instanceof String||param instanceof Number||param instanceof Boolean){
paramStr+="&"+key+"="+encodeURIComponent(param);
}else{
$.each(param,function(i){
var k=key==null?i:key+(param instanceof Array?"["+i+"]":"."+i);
paramStr+='&'+parseParam(this, k);
});
}
return paramStr.substr(1);
};
[javascript] view plain copy
//test
var obj={name:'tom','class':{className:'class1'},classMates:[{name:'lily'}]};
parseParam(obj);
//output: "name=tom&class.className=class1&classMates[0].name=lily"
parseParam(obj,'stu');
//output: "stu.name=tom&stu.class.className=class1&stu.classMates[0].name=lily"
引用自刘家华 http://www.oschina.net/code/snippet_139242_7584
由于是这段代码本身并不算多,为了增强其通用性,我使用了原生Javascript重写了该方法,如下:
/**
* 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
参考来源:https://blog.csdn.net/shawyeok/article/details/41749045