Created
October 17, 2017 02:07
-
-
Save HakurouKen/ed8a1bc04d3e13593e77522b696675d1 to your computer and use it in GitHub Desktop.
A solution for https://github.com/github/fetch/issues/263
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
// codes from https://github.com/madrobby/zepto/blob/601372ac4e3f98d502c707bf841589fbc48a3a7d/src/ajax.js#L344-L37 | |
// serialize the form data for `Content-Type: application/x-www-form-urlencoded` | |
// | |
// Usage Example: | |
// ```javascript | |
// const YOUR_DATA = {foo: "bar", some: "baz"} | |
// fetch('/api/result', { | |
// method: 'POST', | |
// headers: { | |
// 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' | |
// }, | |
// body: param(YOUR_DATA) | |
// }) | |
// ``` | |
function serialize(params, obj, traditional, scope) { | |
let type; | |
let array = Array.isArray(obj); | |
let hash = isPlainObject(obj); | |
Object.keys(obj).forEach(function(key) { | |
let value = obj[key]; | |
type = typeof value; | |
if (scope) | |
key = traditional | |
? scope | |
: scope + | |
'[' + | |
(hash || type == 'object' || type == 'array' ? key : '') + | |
']'; | |
// handle data in serializeArray() format | |
if (!scope && array) params.add(value.name, value.value); | |
else if (type == 'array' || (!traditional && type == 'object')) | |
// recurse into nested objects | |
serialize(params, value, traditional, key); | |
else params.add(key, value); | |
}); | |
} | |
function param(obj, traditional) { | |
let params = []; | |
params.add = function(key, value) { | |
if (typeof value === 'function') value = value(); | |
if (value == null) value = ''; | |
this.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); | |
}; | |
serialize(params, obj, traditional); | |
return params.join('&').replace(/%20/g, '+'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment