convert JS object to POST form data
posted on May 9, 2014, 12:24 am in
Most REST services communicate with JSON, but sometimes you run into a POST form. This code will serialize a JavaScript object to return form data that can be sent for a POST request.
var formStringify = function(obj) {
var formData = "";
for (var key in obj) {
formData += key + "=" + encodeURIComponent(obj[key]) + "&";
}
formData = formData.substring(0, formData.length - 1);
return formData;
};
And its usage:
var data = formStringify({ key : 99, key2 : "bar", key3 : "foo" });
console.log( data );
Check out your browser's console output to see the code in action.