表单序列化

什么是表单序列化尼?

  1 对表单字段的名称和值进行URL编码,使用和号(&)分隔

  2 不发送禁用的表单字段

  3 只发送勾选的复选框和单选按钮

  4 不发送 type 为 reset 和 button的按钮

  5 多选按钮每个选中的值单独一个条目

  6 单击提交按钮提交表单时,会发送提交按钮;否则不发送提交按钮 。也包括前面说过的 type 为 image 的 input 元素。

  7 select元素的值,就是选中的 option元素的value特性的值。如果option元素没有value特性,则是 option元素的文本值。

 

<select> select-one
<select multiple>   select-multiple
<button> submit
<buttom type = button> button
<button type="reset"> reset
<button type="submit"> submit

  

 1 function serialize(form){
 2         var parts = [], field=null,
 3                 i,
 4                 len,
 5                 j,
 6                 optLen,
 7                 option,
 8                 optValue;
 9         for(i=0;len=selectbox.length,i<len;i++){
10             field = selectbox[i];
11             switch(field.type){
12                 case "select-one":
13                 case "select-multiple":
14                     if(field.name.length){
15                         for(j=0,optLen=field.options.length;j<optLen;j++){
16                             option = field.options[j];
17                             if(option.selected){
18                                 optValue = "";
19                                 if(option.hasAttribute){
20                                     optValue = (option.hasAttribute("value")?option.value:option.text)
21                                 }else{
22                                     optValue = (option.attributes["value"].specified?option.value:option.text);
23                                 }
24                                 parts.push(encodeURIComponent(field.name)+"="+encodeURIComponent(optValue));
25                             }
26                         }
27                     }
28                     break;
29                 case undefined://字段集  fieldset
30                 case "file": //文件输入
31                 case "submit"://提交按钮
32                 case "reset": //重置按钮
33                 case "button": //自定义按钮
34                     break;
35                 case "radio"://单选按钮
36                 case "checkbox"://复选框
37                     if(!field.checked){
38                         break;
39                     }
40                 default :
41                     if(field.name.length){
42                         parts.push(encodeURIComponent(field.name)   +   "=" +   encodeURIComponent(field.value));
43                     }
44             }
45         };
46         return parts.join("&");
47     }

 

 

 

posted @ 2016-07-30 17:27  czhyuwj  阅读(325)  评论(0编辑  收藏  举报