怪我咯2017-04-11 09:42:39
仿照着jq写了一个,用法一样的。
function serialize(a, traditional) {
var prefix, s = [];
if ('[object HTMLFormElement]' === Object.prototype.toString.call(a)) a = a.childNodes;
if (["[object Array]", "[object NodeList]"].indexOf(Object.prototype.toString.call(a)) >= 0) {
Array.prototype.forEach.call(a, function(v) {
if (!v.name || v.disabled) return;
if ((v.type === 'radio' || v.type === 'checkbox') && !v.checked) return;
add(v.name, v.value);
});
} else {
for (prefix in a) buildParams(prefix, a[prefix], traditional, add);
}
return s.join("&");
function add(key, valueOrFunction) {
var value = typeof valueOrFunction === 'function' ? valueOrFunction() : valueOrFunction;
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value);
}
function buildParams(t, e, n) {
var r;
if ("[object Array]" === Object.prototype.toString.call(e)) {
Array.prototype.map.call(e, function(e, r) {
o(t + "[" + ("object" == typeof e && null !== e ? r : "") + "]", e, n)
});
} else if ("[object Object]" === Object.prototype.toString.call(e)) {
for (r in e) buildParams(t + "[" + r + "]", e[r], n);
} else {
n(t, e);
}
}
}
测试,点开看效果:
https://jsfiddle.net/ztv676p1/