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

142 篇文章 2 订阅

 

第一层属性的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("出错了,请稍后重试");
                }
            });


        });








其中使用的几个函数为:


 var _fnObjectGetPropertyChainValue = function(obj, propertyChain) {
      /* 获取属性链的值 */
      if (!obj) return;
      if (!propertyChain) return obj;
      var property,
        chains = propertyChain.split('.'),
        i = 0,
        len = chains.length;
      for (;
        (property = chains[i]) && i < len - 1; i++) {
        if (!obj[property]) return;
        obj = obj[property];
      }
      return obj[property];
    },
    _fnObjectSetPropertyChainValue = function(obj, propertyChain, value, allowMulti) {
      /* 设置属性链的值 */
      if (!obj || !propertyChain) return;
      var property,
        chainObj = obj,
        chains = propertyChain.split('.'),
        i = 0,
        len = chains.length;
      for (;
        (property = chains[i]) && i < len - 1; i++) {
        if (!chainObj[property]) {
          chainObj[property] = {};
        }
        chainObj = chainObj[property];
      }
      // 改进版:checkbox的多选可以组合为数组
      if (!allowMulti || chainObj[property] === undefined) {
        chainObj[property] = value;
      } else {
        var pv = chainObj[property];
        if ($.isArray(pv)) {
          pv.push(value);
        } else {
          chainObj[property] = [pv, value];
        }
      }
      return obj;
    };



 /**
     * 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;


  };






    

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张小凡vip

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值