jquery - build pretty url from parameters
jQuery has a param()
function, I'm looking for similar functionality. I need to return a url in my object. For example:
url: function() {
return this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage});
},
this will return a url in the form of example.com/?page=1&perPage=5
or something similar. How can I form the url example.com/page/1/perpage开发者_如何转开发/5
?
You can create your own function:
function build(base, params) {
for(var k in params) {
if(params.hasOwnProperty(k)) {
base += '/' + k + '/' + params[k];
}
}
return base;
}
The only problem is that the order of the parameters is not guaranteed (which is not a problem for query strings but might be for this kind of URLs). You might also want to add a check if base
already ends with a slash or not.
Just an idea :)
'example.com/?page=1&perPage=5'.replace(/[&=]/g,'/').replace('?','')
.toLowerCase();
tack this on the end:
replace(/[&=]/g,'/').replace('?','')
like so:
url: function() {
return (this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage})).replace(/[&=]/g,'/').replace('?','');
},
edited to point out in re to Felix Kling's concern about ?'s: This will only remove the FIRST ? leaving any other ?'s that are part of the query string INTACT. Perfectly safe to use.
精彩评论