表单在js中可以使用表单字段的type属性连同其name属性和value属性来进行序列化
字段名和值是 URL 编码的并以和号(&)分隔。
禁用字段不会发送。
复选框或单选按钮只在被选中时才发送。
类型为”reset”或”button”的按钮不会发送。
多选字段的每个选中项都有一个值。
通过点击提交按钮提交表单时,会发送该提交按钮;否则,不会发送提交按钮。类型为”image”
的元素视同提交按钮。
select元素的值是被选中option元素的 value 属性。如果
返回的结果是查询字符串的格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| function serialize(form){ let parts=[]; let optValue; for(let field of form.elements){ switch(field.type){ case "select-one": case "select-multiple": if(field.name.length){ for(let option of field.options){ if(option.selected){ if(option.hasAttribute){ optValue=(option.hasAttribute("value")?option.value:option.text); }else{ optValue=(option.attributes["value"].specified?option.value:option.text); } parts.push(`${encodeURIComponent(field.name)}=`+`${encodeURIComponent(optValue)}`); } } } break; case undefined: case "file": case "submit": case "reset": case "button": break; case "radio": case "checkbox": if(!field.checked){ break; } default: if(field.name.length){ parts.push(`${encodeURIComponent(field.name)}=`+`${encodeURIComponent(field.value)}`) } } } return parts.join("&"); }
|