原生js序列化表單
function serialize(target) {
let arrFormData = [], objFormData = {},rel = {};
[].slice.call(target.elements).forEach(function (ele) {
let type = ele.type,disabled = ele.disabled,name = ele.name,value = encodeURIComponent(ele.value || '');
if(!name || disabled || !type ||(/^reset|submit|image$/i.test(type)) || (/^checkbox|radio$/i.test(type) && !ele.checked)){
return;
}
type = type.toLocaleLowerCase();
if(type !== 'select-multiple') {
if (objFormData[name]) {
objFormData[name].push(value);
} else {
objFormData[name] = [value];
}
}else{
[].slice.call(ele.querySelector('option')).forEach(function (option) {
let optionValue = encodeURIComponent(option.value || '');
if(option.selected){
if(objFormData[name]){
objFormData[name].push(optionValue);
}else{
objFormData[name] = [optionValue];
}
}
});
}
});
for(let key in objFormData){
arrFormData.push(key+'='+objFormData[key].join());
}
// return arrFormData.join('&');
return objFormData;
}
可以返回json格式數(shù)據(jù)愁铺,也可以返回拼接好的字符串
在最后return的時(shí)候可以選擇返回格式
用的時(shí)候把最后改一下就行了