ajax调用接口传值的几种方式

1、通过requset读取ajax传参:

    @RequestMapping("/addError")
	@ResponseBody
	public Boolean  add(HttpServletRequest request, HttpServletResponse response) {
		ErrorLog eLog = new ErrorLog();
		eLog.setName(request.getParameter("name").toString());
		eLog.setErrorXq(request.getParameter("errorXq").toString());
		eLog.setCreatDate(new Date(System.currentTimeMillis()));
		eLog.setBz(request.getParameter("bz").toString());
		lErrorService.add(eLog);
		return true;
	}



    $.ajax({
       type:'post',
       url:'http://localhost:8080/ssm/addError',
       dataType:'json',
       data:{name:'渣成沙',errorXq:'测试',bz:'yog'},
       success:function (res) {
           resule(res,'新增');
        }
    });

2、通过传实体类方式:

    @RequestMapping("/updateErrorLog")
	@ResponseBody
	public Boolean update(HttpServletRequest request,HttpServletResponse             
                                     response,@RequestBody ErrorLog eLog) {
		
		lErrorService.upErrorXq(eLog);
		return true;
	}


     $.ajax({
         contentType: "application/json; charset=utf-8",
         type:'POST',
         url:'http://localhost:8080/ssm/updateErrorLog',
         data:JSON.stringify(data),
         success:function (res) {

              resule(res,'编辑');
          }
     });

第二种格式使用时遇到两个问题:

1、在ajax请求没有添加 contentType: "application/json; charset=utf-8"时会报 Failed to load resource: the server responded with a status of 415。

2、在ajax请求时没有将参数转成JSON,导致与后台实体不符,切记仔细添加JSON.stringify(data)。

你可能感兴趣的:(开发,JavaScript)