JS form表單採集

來源:互聯網
上載者:User

標籤:input   box   hang   select2   姓名   mod   hasclass   date   res   

做後台系統的時候通常會用到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(/&nbsp;/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() == "" ? "&nbsp;" : $this.val(); if (!$.request("keyValue")) { value = value.replace(/&nbsp;/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表單裡面的欄位和後台類欄位對應,收集起來的對象在後台可以直接使用!

 

JS form表單採集

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.