Last active
August 23, 2016 06:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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