Skip to content

Instantly share code, notes, and snippets.

@yakirn
Last active November 14, 2019 09:58
Show Gist options
  • Save yakirn/831e5e7fcdfb50fc6c94 to your computer and use it in GitHub Desktop.
Save yakirn/831e5e7fcdfb50fc6c94 to your computer and use it in GitHub Desktop.
A modified version of serialize and param methods from zeptos, that depends on _ as a global var (tested on [email protected])
/* 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 [email protected], 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, '+')
}
@sandrosc
Copy link

ah yes, was more a comment for people which might come here later from google ^^. Thanks for your response :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment