正文开始 实现原理,先封装一个表单提交时的自定义参数控制方法,然后遍历所有文件,让文件选择时自动打包formdata到临时的对象,待表单提交时再一起打包合并即可。
~~~
formSubmitEven : function(form, opt) {
var beforeFunc = backObj.getOptVal(opt, ['before'], null);
var files = form.find("input[type='file']");
var fileData = {};
files.on('change', function () {
let fileObj = $(this);
let inputName = $(this).attr('name');
let fileNode = fileObj[0].files[0];
let reader = new FileReader();
reader.onload = function (e) {
let base64Data = e.target.result;
fileData[inputName] = base64Data;
};
reader.readAsDataURL(fileNode);
});
form.on('submit', function (e) {
e.preventDefault();
e.stopPropagation();
var data_ = form.serializeArray();
var pData = {};
pData = $.extend(pData, fileData);
data_.map(function (v, n) {
if(!backObj.isUndefined(pData[v.name])) {
if($.isArray(pData[v.name])) {
pData[v.name].push(v.value);
} else {
pData[v.name] = [pData[v.name], v.value];
}
} else {
pData[v.name] = v.value;
}
});
if(beforeFunc) {
var status = beforeFunc(pData);
if(status===false) {
return;
}
}
if(!backObj.isUndefined(opt['postData'])) {
opt['postData'].map(function (v, k) {
pData[k] = v;
});
}
var newOpt = {
'postData' : pData
};
var onSubmit = !backObj.isUndefined(opt['submit']) ? opt['submit'] : false;
if(onSubmit) onSubmit(form);
newOpt = $.extend({}, newOpt, opt);
backObj.postAndDone(newOpt);
});
},
~~~
请求示例:
~~~
front.formSubmitEven(form_, {
before: function (res) {
var email = res['row[email]'];
if (!email) {
lrBox.msgTisf("Please fill in your email address.");
return false;
}
var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
if (!reg.test(email)) {
lrBox.msgTisf("Mailbox format is not correct");
return false;
}
lrBox.loadingSvg(true);
},
url: '/visitor/upload_electricity_bill',
successKey: 'code',
successVal: 1,
successFunc: function (res) {
lrBox.noLoading();
lrBox.msgTisf(res.msg);
front.cleanForm(form_);
},
errorFunc: function (res) {
lrBox.noLoading();
lrBox.msgTisf(res.msg);
}
});
~~~
正文结束 |
js 正则替换返回值做回调函数 | js 动态传参 将内部函数作为接口暴露给当前对象 arguments的动态传递给其他方法 |