做后台系统的时候通常会用到form表单来做数据采集;每次一个字段一个字段的去收集就会很麻烦,网站也有form.js插件可以进行表单收集,并封装成一个对象,通过ajax方法传到后台;现在介绍一种直觉采集form表单的方式:
1.首先写一段公用的js:
//收集表单数据为一个数组
$.request = function (name) {
var search = location.search.slice(1);
var arr = search.split("&");
for (var i = 0; i < arr.length; i++) {
var ar = arr[i].split("=");
if (ar[0] == name) {
if (unescape(ar[1]) == \'undefined\') {
return "";
} else {
return unescape(ar[1]);
}
}
}
return "";
}
$.fn.formSerialize = function (formdate) {
var element = $(this);
if (!!formdate) {
for (var key in formdate) {
var $id = element.find(\'#\' + key);
var value = $.trim(formdate[key]).replace(/ /g, \'\');
var type = $id.attr(\'type\');
if ($id.hasClass("select2-hidden-accessible")) {
type = "select";
}
switch (type) {
case "checkbox":
if (value == "true") {
$id.attr("checked", \'checked\');
} else {
$id.removeAttr("checked");
}
break;
case "select":
$id.val(value).trigger("change");
break;
default:
$id.val(value);
break;
}
};
return false;
}
var postdata = {};
element.find(\'input,select,textarea\').each(function (r) {
var $this = $(this);
var id = $this.attr(\'id\');
var type = $this.attr(\'type\');
switch (type) {
case "checkbox":
postdata[id] = $this.is(":checked");
break;
default:
var value = $this.val() == "" ? " " : $this.val();
if (!$.request("keyValue")) {
value = value.replace(/ /g, \'\');
}
postdata[id] = value;
break;
}
});
if ($(\'[name=__RequestVerificationToken]\').length > 0) {
postdata["__RequestVerificationToken"] = $(\'[name=__RequestVerificationToken]\').val();
}
return postdata;
};