js实现表单序列化的两种方法。

function serialize(form) {
var parts = [],
elems = form.elements,
i = ,
len = elems.length,
filed = null;
for (; i < len; i++) {
filed = elems[i];
switch (filed.type) {
case "select-one":
case "select-multiple":
if (filed.name.length) {
var j = ,
opt,
optLen = filed.options.length;
for (; j < optLen; j++) {
opt = filed.options[j];
if (opt.selected) {
parts.push(encodeURIComponent(filed.name) + "=" + encodeURIComponent(opt.value));
}
}
}
break;
case undefined:
case "submit":
case "reset":
case "file":
case "button":
break;
case "radio":
case "checkbox":
if (!filed.checked) {
break;
}
default:
if (filed.name.length && filed.value) {
parts.push(encodeURIComponent(filed.name) + "=" + encodeURIComponent(filed.value));
}
}
}
return parts.join("&");
}

这个方法重点用了HTML5中的FormData ,还有es6中for of循环。

  function serialize(form) {
var formData = new FormData(form),
getValue = formData.entries(),
parts = [];
for (var pair of getValue) {
parts.push(pair[] + "=" + pair[]);
}
return parts.join("&");
}
上一篇:小红书shield分析转发


下一篇:Step by step Process of creating APD