前端提交的几种方式

 

 

 

后台接收代码:

@PostMapping("/post/a")
 public String postA(User user){
        System.out.println("/post/a");
        System.out.println(user);
        return user.toString();
 }

 @PostMapping("/post/b")
 public String postB(@RequestBody User user){
     System.out.println("/post/b");
     System.out.println(user);
     return user.toString();
 }

对于 postA方法,则前端的提交方式为:

contentType:"application/x-www-form-urlencoded"

data:$("#formId").serializaArray() / 或者 data: $('#form1').serialize(),

----------------

对于 postB方法,则前端的提交方式为:

contentType:"application/json"

data:JSON.stringify(data)

 ---------------------------------------------------------------------------------------------------------------------------

如果请求提交一个list集合:

前端代码:

<form id="inputForm" th:action="@{'/messageTpl/save'}" method="post">
    
                    <input type="hidden" th:name="|messageTpls[0].createDate|" th:value="${tpl.createDate}"/>
                    <input type="hidden" th:name="|messageTpls[0].delFlag|" th:value="${tpl.delFlag}"/>
 <input type="hidden" th:name="|messageTpls[1].createDate|" th:value="${tpl.createDate}"/>
                    <input type="hidden" th:name="|messageTpls[1].delFlag|" th:value="${tpl.delFlag}"/>
<input type="button" class="button" value="提交" onclick="sendListData()"/>
</form>
<script>
function sendListData() {
        var params = {};
        var t = $("form:eq(0)").serializeArray();
        $.each(t, function () {
            params[this.name] = this.value;
        });
        const action = $("form:eq(0)").attr("action").replace("/back", "");
        $.ajax({
            url: baseUrl + action,
            async: true,
            type: 'POST',
            data: params,
            contentType: "application/x-www-form-urlencoded",//表单提交
            dataType: "json",
            success: function (res) {
            }
        })
}
</script>        
View Code

后台代码:

   @PostMapping("/save")
   @ResponseBody
   public RestResponse saveSmsTpl(MessageTplReq req) {
   }

   public class MessageTplReq {

      private List<MessageTpl> messageTpls;
      getter...
      setter...  
  }

 

posted @ 2018-12-05 23:13  戴眼镜的蚂蚁  阅读(964)  评论(0编辑  收藏  举报