表单(四)表单序列化
生活随笔
收集整理的這篇文章主要介紹了
表单(四)表单序列化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
表單序列化的作用是:將表單內容序列化成一個字符串,方便Ajax傳遞表單值給服務器。
【瀏覽器把表單數據提交到服務器的細節】:
1. 對字段的名和值進行URL編碼,并使用“&”分隔 2. 不發送禁用的字段 disabled 3. 多選框中每個選中的名值對是單獨的一個條目 4. 在<select>元素中,option如果沒有value特性,則值為option的文本值text 5. 不發送button、reset、submit、file字段的名值對 var form = document.getElementById("表單ID"); function serialize(form){var parts = [], //保存字段和對應值的一個數組field = null,i,len,j,optLen,option,optValue;for(i=0,len = form.elements.length;i<len;i++){field = form.elements[i];switch(field.type){case "select-one":case "select-multiple":if(field.name.length){for(j=0,optLen=field.options.length;j<optLen;j++){option = field.options[j];if(option.hasAttribute){optValue = (option.hasAttribute("value")? option.value : option.text);}//IEelse{optValue = (option.attributes["value"].specified ? option.value : option.text);}parts.push(encodeURIComponent(field.name) +"="+ encodeURIComponent(optValue));}}break;case undefined: //fieldset元素沒有type屬性case "file":case "button":case "reset":case "submit":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("&"); }總結
以上是生活随笔為你收集整理的表单(四)表单序列化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 圈复杂度Cyclomatic compl
- 下一篇: springboot视图解析器配置