牛骨文教育服务平台(让学习变的简单)
博文笔记

Form表单传递List数组属性到后台对象中

创建时间:2017-05-04 投稿人: 浏览次数:213


第一层属性的List


后台有一个对象 User ,结构如下:


public class User{

 private String username;


 private List<PhotoDo> photo;


 ..get ....set.....


}


public class PhotoDo{

 private String id;


 private String name;


  ...get...set...

}

Controller中接受方法 getUser


@reqeustMapping("/getUser")

public void getUser(User user){


...实现方法...


}


前台Form这么写:


<form>

     <input type="text" name="username" aciton="..">


     <input type="text" name="photo[0].id">

     <input type="text" name="photo[0].name">

     <input type="text" name="photo[1].id">

     <input type="text" name="photo[1].name">

     <input type="text" name="photo[2].id">

     <input type="text" name="photo[2].name">

</form>




第二层属性的List


如果List属性不是在User属性的第一层,而是在第二层,则需要处理一下。


后台有一个对象 User ,结构如下:


public class User{
 private String username;


 private Address address;


 ..get ....set.....


}






public class Address{
 private List<PhotoDo> photo;


 ..get ....set.....


}




public class PhotoDo{
 private String id;


 private String name;


  ...get...set...
}


Controller中接受方法 getUser


@reqeustMapping("/getUser")
public void getUser(User user){


...实现方法...


}


前台Form这么写:


<form>
     <input type="text" name="username" aciton="..">


     <input type="text" name="address.photo[0].id">
     <input type="text" name="address.photo[0].name">
     <input type="text" name="address.photo[1].id">
     <input type="text" name="address.photo[1].name">
     <input type="text" name="address.photo[2].id">
     <input type="text" name="address.photo[2].name">
</form>




Js中需要作处理:


  $("button.save").on("click", function () {
            debugger;
            var data = $("#user").formGet();
            var photos = new Array();
            for (var i in data.address) {
                photos.push(data.address[i]);
            }
            data.photos= photos;
            $.ajax({
                type: "POST",
                url: "/user/save",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (result) {
                    console.log(result);
                    if (!result.code) {
                        $("#mutation").formSet(data);
                        location.href = "/user"
                    } else {
                        alert(result.msg);
                    }
                },
                error: function () {
                    alert("出错了,请稍后重试");
                }
            });


        });








其中使用的几个函数为:
 /**
     * jQuery form 扩展获取数据
     */
  $.fn.formGet = function(opts) {
    opts = $.extend({}, opts);
    var data = {},
      els = opts.formGroup ? this.find("[form-group="" + opts.formGroup + ""]") : this.find("[name]");
    if (!els || !els.length) {
      return data;
    }


    var fnSetValue = (function(emptyToNull) {
      return emptyToNull ? function(obj, propertyChain, value, allowMulti) {
        value !== "" && _fnObjectSetPropertyChainValue(obj, propertyChain, value, allowMulti)
      } : _fnObjectSetPropertyChainValue
    })(opts.emptyToNull);


    els.each(function() {
      var $this = $(this),
        type = $this.attr("type"),
        name = $this.attr("name"), // 可能为属性链
        tag = this.tagName.toLowerCase();
      if (tag == "input") {
        if (type == "checkbox") {
          var v = $(this).val();
          if (v == "on" || !v) {
            fnSetValue(data, name, $(this).prop("checked"));
          } else {
            $(this).prop("checked") && fnSetValue(data, name, v, true);
          }
        } else if (type == "radio") {
          this.checked && fnSetValue(data, name, $this.val());
        } else {
          fnSetValue(data, name, $this.val());
        }
      } else if ("|select|textarea|".indexOf("|" + tag + "|") > -1) {
        fnSetValue(data, name, $this.val());
      } else {
        fnSetValue(data, name, $.trim($this.text()));
      }
    });
    return data;
  };


  /**
     * jQuery form 扩展绑定数据
     * 
     */
  $.fn.formSet = function(data, formGroup) {
    var els = formGroup ? this.find("[form-group="" + formGroup + ""]") : this.find("[name]");
    if (!els || !els.length) {
      return this;
    }


    els.each(function() {
      var $this = $(this),
        type = $this.attr("type"),
        name = $this.attr("name"),
        tag = this.tagName.toLowerCase();


      var value = _fnObjectGetPropertyChainValue(data, name);
      if (tag == "input") {
        if (type == "checkbox") {
          var v = $(this).val();
          if (v == "on" || !v) {
            this.checked = value ? "checked" : "";
          } else {
            this.checked = $.isArray(value) && value.indexOf(v) > -1 ? "checked" : ""
          }
        } else if (type == "radio") {
          this.checked = $this.val() == String(value) ? "checked" : "";
        } else {
          $this.val(value);
        }
      } else if ("|select|textarea|".indexOf("|" + tag + "|") > -1) {
        $this.val(value);
      } else {
        $this.html(value);
      }
    });
    return this;
  };






    


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。