/* the following serialize and param methods are a version of zepto's
* https://github.com/madrobby/zepto/blob/601372ac4e3f98d502c707bf841589fbc48a3a7d/src/ajax.js#L344-L370
* modified to use _ (tested on lodash@4.6.1, should also work in underscore)
* to use with github's fetch:
fetch(urrl, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
body: params({key1: "value1", key2: "value2"})
})
*/
function serialize(params, obj, traditional, scope){
var type, array = _.isArray(obj), hash = _.isObject(obj)
_.each(obj, function(value, 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)
// recurse into nested objects
else if (type == "array" || (!traditional && type == "object"))
serialize(params, value, traditional, key)
else params.add(key, value)
})
}
function param(obj, traditional){
var params = []
params.add = function(key, value) {
if (_.isFunction(value)) value = value()
if (value == null) value = ""
this.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
}
serialize(params, obj, traditional)
return params.join('&').replace(/%20/g, '+')
}