ajax-springMVC提交表单的方式

1.request参数提交(Form提交),适用于GET/POST

request参数传递都会转换成 id=123&fileName=test.name&type=culture_art这种形式,get请求会显示在url上,post不在url上显示

ajax写法:

$.ajax({
        url : /admin/test,
        type : "post",
        async : true,//默认为true
        contentType: application/x-www-form-urlencoded, //默认值为表单提交
        data : {"id" : id,"fileName" : fileName,"type" : modelType},//请求参数
        success : function(data) {
            //请求成功处理
        },
        error : function(data) {
            //请求失败处理
        }
});

controller

第1,2种写法controller形参和ajax data中的key必须保持一致

第3种写法形参可以不一致,@requestParam中的vaue必须和data中的key一致才能自动参数绑定)

第1种写法
@PostMapping("/admin/test") public ResultBean<String> updateModelNameAndType(
  String id,
  String fileName,
  String type) {
return null; }
第2种写法 @PostMapping(
"/admin/test") public ResultBean<String> updateModelNameAndType(
   @RequestParam String id,
  @RequestParam String fileName,
   @RequestParam String type) {
return null; }
第3种写法 @PostMapping(
"/admin/test") public ResultBean<String> updateModelNameAndType(
  @RequestParam(value="id") String tmpId,
  @RequestParam(value="fileName") String tmpFileName,
  @RequestParam(value="type") String tmpType) { return null; }
第4种写法(封装成bean,bean的属性名称和ajax data中的key一致即可自动绑定到对象)
@PostMapping("/admin/test")
public ResultBean<String> updateModelNameAndType(ModelInfo modelInfo) {
      return null;
}

2.request body提交,适用于POST提交

注意将ajax中data的值json对象转成json字符串

ajax

$.ajax({
    url : "/admin/test",
    type : "post",
    contentType : "application/json;charset=UTF-8",
    data : JSON.stringify({id:"id",fileName:"test.txt"}),//或者直接获取form表单 data : $('#form').serialize()
    success : function(data) {
        
    },
    error : function(data) {
        
    }
});

controller

@PostMapping("/admin/test")
public ResultBean<String> insertNewVersion(@RequestBody VersionEntity versionInfo) {
  return service.getVersionSvc().insertVersion(versionInfo);
}

猜你喜欢

转载自www.cnblogs.com/zincredible/p/10236268.html