jQuery 有一个param()
功能,我正在寻找类似的功能。我需要在我的对象中返回一个 url。例如:
url: function() {
return this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage});
},
这将返回一个 urlexample.com/?page=1&perPage=5
或类似的形式。我怎样才能形成网址example.com/page/1/perpage/5
?
jQuery 有一个param()
功能,我正在寻找类似的功能。我需要在我的对象中返回一个 url。例如:
url: function() {
return this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage});
},
这将返回一个 urlexample.com/?page=1&perPage=5
或类似的形式。我怎样才能形成网址example.com/page/1/perpage/5
?
您可以创建自己的函数:
function build(base, params) {
for(var k in params) {
if(params.hasOwnProperty(k)) {
base += '/' + k + '/' + params[k];
}
}
return base;
}
唯一的问题是不能保证参数的顺序(这对于查询字符串不是问题,但可能是这种 URL)。您可能还想添加一个检查是否base
已经以斜线结尾。
只是一个想法:)
'example.com/?page=1&perPage=5'.replace(/[&=]/g,'/').replace('?','')
.toLowerCase();
最后解决这个问题:
replace(/[&=]/g,'/').replace('?','')
像这样:
url: function() {
return (this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage})).replace(/[&=]/g,'/').replace('?','');
},
编辑以重新指出 Felix Kling 对 ?'s 的关注:这只会删除 FIRST ? 保留作为查询字符串 INTACT 一部分的任何其他?完全安全使用。