Skip to content

Instantly share code, notes, and snippets.

@ordinz
Created November 12, 2010 16:10
Show Gist options
  • Save ordinz/674274 to your computer and use it in GitHub Desktop.
Save ordinz/674274 to your computer and use it in GitHub Desktop.
http_build_query.js
function urlencode (str) {
str = (str+'').toString();
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
};
function http_build_query(formdata, numeric_prefix, arg_separator){
var value, key, tmp = [], that = this;
var _http_build_query_helper = function (key, val, arg_separator) {
var k, tmp = [];
if (val === true) {
val = "1";
} else if (val === false) {
val = "0";
}
if (val !== null && typeof(val) === "object") {
for (k in val) {
if (val[k] !== null) {
tmp.push(_http_build_query_helper(key + "[" + k + "]", val[k], arg_separator));
}
}
return tmp.join(arg_separator);
} else if (typeof(val) !== "function") {
return that.urlencode(key) + "=" + that.urlencode(val);
} else if (typeof(val) == "function") {
return '';
} else {
throw new Error('There was an error processing for http_build_query().');
}
};
if (!arg_separator) {
arg_separator = "&";
}
for (key in formdata) {
value = formdata[key];
if (numeric_prefix && !isNaN(key)) {
key = String(numeric_prefix) + key;
}
tmp.push(_http_build_query_helper(key, value, arg_separator));
}
return tmp.join(arg_separator);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment