封装:获取序列化from表单数据
class serializeForm {
constructor(options={}){
this.form=options.form
}
getElements() {
const tagElements = this.form.querySelectorAll('input,select,textarea');
if (tagElements.length > 0) {
return Array.from(tagElements);
}
try {
console.error(new Error('当前form没有表单内容,请检查后再试'));
} catch (error) {
console.log(error);
}
return false;
}
serializeElement(element) {
let method = element.type.toLowerCase();
if(method == 'select-one' || method =='textarea'){
return [element.name, element.value];
}
if (['text', 'password', 'number', 'file', 'color', 'hidden', 'date','search','email','tel','url'].includes(method)) {
return [element.name, element.value];
} else if (['checkbox', 'radio'].includes(method)) {
if (element.checked){
return [element.name, element.value];
}
}
return false;
}
codeurl(parameter){
if (parameter) {
let key = encodeURIComponent(parameter[0]);
if (key.length == 0) return;
if (parameter[1].constructor != Array) parameter[1] = [parameter[1]];
let values = parameter[1];
let results = [];
for (let i = 0; i < values.length; i++) {
results.push(key + '=' + encodeURIComponent(values[i]));
}
return results;
}
}
serializeUrlForm() {
let elements = this.getElements();
let queryComponents = new Array();
for (let i = 0; i < elements.length; i++) {
let queryComponent = this.serializeElement(elements[i]);
if(queryComponent){
queryComponent=this.codeurl(queryComponent)
if (queryComponent) {
queryComponents.push(queryComponent);
}
}
}
return queryComponents.join('&');
}
serializeForm() {
let elements = this.getElements();
let queryComponents = {};
for (let i = 0; i < elements.length; i++) {
let queryComponent = this.serializeElement(elements[i]);
if(queryComponent){
let KEY=queryComponent[0]
let VALUE=queryComponent[1]
if (queryComponents[KEY]) {
if(Object.prototype.toString.call(queryComponents[KEY])=='[Object Array]'){
queryComponents[KEY].push(VALUE)
}else{
queryComponents[KEY]=[queryComponents[KEY],VALUE];
}
}else{
queryComponents[KEY]=VALUE
}
}
}
return queryComponents;
}
}
const fromitem= document.getElementById('fromid')
let text=new serializeForm({
form:fromitem
})
function onfrom(){
console.log(text.serializeForm())
console.log(text.serializeUrlForm())
}