Skip to content

Instantly share code, notes, and snippets.

@filipbech
Last active August 23, 2016 06:30
Show Gist options
  • Save filipbech/0bdf23b2c6c7c0972c785316092bceff to your computer and use it in GitHub Desktop.
Save filipbech/0bdf23b2c6c7c0972c785316092bceff to your computer and use it in GitHub Desktop.
Using the native fetch-api to send POST-request encoded like jQuery.ajax does it.
fetch('/endpoint', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: serialize({
value: 1,
nested: {
value: '2'
}
})
})
.then(response => response.json())
.then(data => {
console.log('Succes', data);
});
function serialize(obj, prefix) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment