原生JS实现表单序列化serialize()
生活随笔
收集整理的這篇文章主要介紹了
原生JS实现表单序列化serialize()
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
有一個(gè)form表單,要用AJAX后臺(tái)提交,原來(lái)想拼接json,但是數(shù)據(jù)多了麻煩,不靈活。
用HTML5的FormData來(lái)初始化表單
var formdata=new FormData(document.getElementById("advForm"));
看似還可以,但發(fā)現(xiàn)有兩個(gè)問(wèn)題,
一,formdata.get()方法不知為什么用不了
二,F(xiàn)orm Data 數(shù)據(jù)格式不如Jq的簡(jiǎn)潔,
WebKitFormBoundary29h06FRZequJgQtR
var stu={
name:"冷榮富",
age:22,
sex:"男"
};
$.ajax({
type : "POST", //提交方式
url : "http://localhost/jsonTest.php",//路徑,www根目錄下
data : {
"student" : stu
},//數(shù)據(jù),這里使用的是Json格式進(jìn)行傳輸
success : function(result) {//返回?cái)?shù)據(jù)根據(jù)結(jié)果進(jìn)行相應(yīng)的處理
alert(result);
}
});
這段JQ提交的數(shù)據(jù)是序列化的
網(wǎng)查如然不用我造輪子了,轉(zhuǎn)一個(gè)可用的
使用原生的js模擬了表單序列化,代碼中對(duì)表單處理盡可能地進(jìn)行文字說(shuō)明
其中對(duì)于url,字段名稱,中文進(jìn)行了使用了encodeURIComponent()進(jìn)行編碼。
Object.prototype.serialize = function(){
var res = [], //存放結(jié)果的數(shù)組
current = null, //當(dāng)前循環(huán)內(nèi)的表單控件
i, //表單NodeList的索引
len, //表單NodeList的長(zhǎng)度
k, //select遍歷索引
optionLen, //select遍歷索引
option, //select循環(huán)體內(nèi)option
optionValue, //select的value
form = this; //用form變量拿到當(dāng)前的表單,易于辨識(shí)
for(i=0, len=form.elements.length; i<len; i++){
current = form.elements[i];
//disabled表示字段禁用,需要區(qū)分與readonly的區(qū)別
if(current.disabled) continue;
switch(current.type){
//可忽略控件處理
case "file": //文件輸入類型
case "submit": //提交按鈕
case "button": //一般按鈕
case "image": //圖像形式的提交按鈕
case "reset": //重置按鈕
case undefined: //未定義
break;
//select控件
case "select-one":
case "select-multiple":
if(current.name && current.name.length){
console.log(current)
for(k=0, optionLen=current.options.length; k<optionLen; k++){
option = current.options[k];
optionValue = "";
if(option.selected){
if(option.hasAttribute){
optionValue = option.hasAttribute('value') ? option.value : option.text
}else{
//低版本IE需要使用特性 的specified屬性,檢測(cè)是否已規(guī)定某個(gè)屬性
optionValue = option.attributes('value').specified ? option.value : option.text;
}
}
res.push(encodeURIComponent(current.name) + "=" + encodeURIComponent(optionValue));
}
}
break;
//單選,復(fù)選框
case "radio":
case "checkbox":
//這里有個(gè)取巧 的寫(xiě)法,這里的判斷是跟下面的default相互對(duì)應(yīng)。
//如果放在其他地方,則需要額外的判斷取值
if(!current.checked) break;
default:
//一般表單控件處理
if(current.name && current.name.length){
res.push(encodeURIComponent(current.name) + "=" + encodeURIComponent(current.value));
}
}
}
return res.join("&");
}
對(duì)HTML表單使用:
formElement.serialize();
得到類似如下結(jié)果:a=1&b=2&c=3&d=4&e=5
相關(guān)鏈接:https://blog.csdn.net/qq_35087256/article/details/81253559
總結(jié)
以上是生活随笔為你收集整理的原生JS实现表单序列化serialize()的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: pandas 每一列相加_Python数
- 下一篇: PageInfo的介绍与使用