post请求 传递json对象和json字符串

1.post请求方式一,指定contentType

contentType为application/json时,data的类型要转换成json字符串的形式

$.ajax({
   type : "POST",
   url : "/mailbox/sendMail/resend",
   dataType : "json",
   data : JSON.stringify(ids),
   contentType:"application/json;charset=utf-8",
   success : function(d) {
     alert("成功");
   }
});

后台接收:要使用@RequestBody注解接收前端传递的参数

 @RequestMapping(value = "/resend", produces = "application/json;charset=utf-8")
 public @ResponseBody String resend(@RequestBody List<Long> ids) {
     return "success";
  }

 再如前端请求

	$.ajax({
				type : "post",
				url : "/intelligentAllocate/createAllocateDemand",
				data : JSON.stringify(obj),
				contentType:'application/json;charset=utf-8',
				dataType : "json",
				success : function(data) {
		
				}
			});

后台接收

@RequestMapping(value = "/createAllocateDemand", produces = "application/json;charset=utf-8")
	public @ResponseBody String createAllocateDemand(@RequestBody AllocateDemandPoJo demandPoJo) {
		Result result = this.getResult();
		try{
			try {
				User user = this.getLoginUser();
				demandPoJo.setCode(orderNumberService.nextOrderCode(OrderType.DB.name(), user));
				demandPoJo.setType("SALE");
				long num = allocateDemandService.add(demandPoJo, user);
				if(num>0){//添加成功
					result.setCode(ResultStatus.SUCCESS);
				}else{//添加失败
					result.setCode(ResultStatus.FALSE);
				}
			} catch (Exception e) {
				e.printStackTrace();
				result.setCode(ResultStatus.ERROR);
			}
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setCode(ResultStatus.FALSE);
			result.addMsg(e.getMsg());
		} catch(Exception e){
			e.printStackTrace();
		}
		return this.getI18nResult(result);
	}

2.post请求方式二:$.post() 方法使用 HTTP POST 请求从服务器加载数据。

请求的参数是json对象类型

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

$.post(
"/amazonReport/reportSearch/1/50", 
{ name: "John", time: "2pm" }, 
function(data) {
   console,log(data);
 });

后台接收

@RequestMapping(value = "/reportSearch/{pageNum}/{pageSize}", produces = "application/json;charset=utf-8")
	public ModelAndView reportSearch(AmazonReportRequestInfo amazonReportRequestInfo, HttpServletRequest request, HttpSession session,
									 Boolean defaultSearch) {
        return null;
}

3.如果前端使用 $.post()方式提交请求  ,data所传数据类型为json字符串,后端使用@RequestBody接收请求参数时会报错

 Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)

使用post方式提交请求 使用方式1  或者方式2  ,混合使用会导致3这种报错

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值