JS form 表单收集 数据 formSerialize
做后台系统的时候通常会用到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; };
2.使用方法
html代码:
<form id='form1id'>
姓名:<input type='text' id='names' name='names'/><br/>
年龄:<input type='text' id='names' name='names'/>
</form>
js代码:
var infoModel = JSON.stringify($("#form1id").formSerialize());//得到手机到的表对象
$.ajax({
type: "Post",
url: "/HRSSC/Resume/" + Act,
data: "{infoModel:" + infoModel + "}",//前面的命名和后台接收参数一直
dataType: "json",
contentType: "application/json",
success: function (result) {console.log(result);}
后台代码:
public ActionResult AddEmp(Empinfo infoModel) //命名和前台ajax传的参数一致
{
//具体业务处理
return view();
}
只要把form表单里面的字段和后台类字段对应,收集起来的对象在后台可以直接使用!