原生表單序列化
隨著Ajax的出現(xiàn),表單序列化已經(jīng)成為一種需求,在學(xué)習(xí)原生Ajax時(shí),若用POST方法向后臺(tái)提交數(shù)據(jù)時(shí),就需要將表單序列化
在JavaScript中可以利用表單字段的type屬性,連同name和value屬性,一起實(shí)現(xiàn)表單的序列化。
在進(jìn)行表單序列化之前,需要弄清楚在表單提交期間,瀏覽器是怎樣將數(shù)據(jù)發(fā)送給服務(wù)器的。
實(shí)現(xiàn)表單序列化的函數(shù)為:
function serialize(form){var parts=[],field=null,i,len,j,optLen,option,optValue;for (i = 0; i < form.elements.length; i++) {field=form.elements[i];switch (field.type) {case 'select-one':case 'select-multiple':if(field.name.length){for (var j = 0; j < field.options.length; j++) {option=field.options[j];if (option.selected) {optValue="";if (option.hasAttribute) {optValue=(option.hasAttribute('value') ? option.value : option.text);}else{optValue=(option.attribute['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": //復(fù)選框if (!field.checked) {break;}//執(zhí)行默認(rèn)操作default://不包含沒有名字的表單字段if(field.name.length){parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));}}}return parts.join("&");}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選