Skip to content

Instantly share code, notes, and snippets.

@noc2spam
Forked from luk-/http_build_query.js
Created August 16, 2016 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noc2spam/3745c82b67120e163f61edb9c424b108 to your computer and use it in GitHub Desktop.
Save noc2spam/3745c82b67120e163f61edb9c424b108 to your computer and use it in GitHub Desktop.
php's http_build_query() in javascript
var build_query = function (obj, num_prefix, temp_key) {
var output_string = []
Object.keys(obj).forEach(function (val) {
var key = val;
num_prefix && !isNaN(key) ? key = num_prefix + key : ''
var key = encodeURIComponent(key.replace(/[!'()*]/g, escape));
temp_key ? key = temp_key + '[' + key + ']' : ''
if (typeof obj[val] === 'object') {
var query = build_query(obj[val], null, key)
output_string.push(query)
}
else {
var value = encodeURIComponent(obj[val].replace(/[!'()*]/g, escape));
output_string.push(key + '=' + value)
}
})
return output_string.join('&')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment