ajax返回 Json的几种方式(Java)

方式一:手写代码自己转json

$.ajax({
data : {
// userNameOrTel: $("#user").val(),
// password: $("#pwd").val()
},
type : "post", 
url : "admin/login/",
dataType : "json",
contentType : "application/json;charset=utf-8", 
async : false, //同步 异步
success : function(data) {
debugger; 
}
}
});
@RequestMapping(value="/haha")
public string xxx { HttpHttpServletRequest request,HttpServletResponse response} 
{ JSONObject json =new JSONObject();
json.put("result"," success")
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = null;
out = response.getWriter();
out.write(json.toString()); 
}

======================================================================================

方式二:

<script type="text/javascript">
        var requestAjax = function() {
            $.ajax({
                type:"post",
                url: 'getDemoList.do',
                data: '',
                dataType:"json",
                success:function(rd){
                    console.log(rd);
                    var dataJson = JSON.stringify(rd);
                    document.write(dataJson);
                },
                error:function(){
                    
                }
            });
        }
        $(function() {
            requestAjax();
        });
    </script>
    @RequestMapping(value="/admin/sys/getDemoList")
    @ResponseBody
    public Map<String, Object> getDemoList(Ips bsSysUsers, Integer page, Integer limit){
        Map<String, Object> map = ResultMapUtil.getMap();
        if (page == null) {
            page = 1;
        }
        if (limit == null) {
            limit = 50;
        }
        PageModel<Ips> list = ipsServiceImpl.selUserListByName(bsSysUsers, page, limit);
        map.put("succ", true);
        map.put("msg", "get ip success");
        map.put("data", list);
        return map;
    }

======================================================================================

          function addcustomber(){
                 if(!$('#customerAddForm').isValid()){return false;};
                  var postdata={
                     customerNumber:$.trim($("#customerNumber").val()),
                       customberName:$.trim($("#customberName").val()), 
                     customerTypeid:$.trim(customerTypeidbox.getValue()), 
                     customerLevel:$.trim(customerLevelbox.getValue()), 
                     customerBalanceDate:$.trim($("#customerBalanceDate").val()), 
                     customberReceivables:HsyErpMain.currencyToNum($.trim($("#customberReceivables").val())), 
                     customberPrepayment:HsyErpMain.currencyToNum($.trim($("#customberPrepayment").val())),
                     customberRemarks:$.trim($("#customberRemarks").val()),
                     contactsList:checkcontact()
                  };
                  disabut();
                  $.ajax({
                    type : 'POST',
                    contentType: "application/json; charset=utf-8",
                    data :JSON.stringify(postdata),
                  /*data :{"customerId":rowData.customerId},*/
                    url : 'addcutombers.wy',
                    dataType: "json",
                    success : function(a){
                      if(!!a.status){
                           W.$.dialog.tips(a.msg,1,'succ.png');
                           W.$("#rld").click();
                           dialog.close();
                      }else{
                         W.$.dialog.tips(a.msg,1,'err.png');                 
                      }
                      undisabut();
                     },
                     error:function(a){
                        W.$.dialog.tips("服务器端响应失败,请重试...",1,'err.png');
                        undisabut();
                     }
                  }); 
        
              return false;
          }
    @RequestMapping(value = "addcutombers", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String addCutombers(@RequestBody CustombersExt custombersExt){
            //custombersExt.setCustomberCuid(bsu.getUserId());
            //custombersExt.setCustomberCdate(new Date());
            Map<String, Object> map = new HashMap<String, Object>();
            int RI = custombersServiceImpl.add_Custombers(custombersExt);
            if(RI>0){
                map.put("status", 1);
                map.put("msg", "新增客户成功");
            }else if(RI==-1){
                map.put("status",0);
                map.put("msg", "新增客户失败.客户编号不能重复!");
            }else{
                map.put("status",0);
                map.put("msg", "新增客户失败.请重试...");
            }
            try {
                ObjectMapper mapper = new ObjectMapper();
                return mapper.writeValueAsString(map);
            } catch (JsonProcessingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        return null;
    }    

======================================================================================

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);
GET方式无请求体,所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。
在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。
注:一个请求,只有一个RequestBody;一个请求,可以有多个RequestParam。

注:当同时使用@RequestParam()和@RequestBody时,@RequestParam()指定的参数可以是普通元素、
       数组、集合、对象等等(即:当,@RequestBody 与@RequestParam()可以同时使用时,原SpringMVC接收
       参数的机制不变,只不过RequestBody 接收的是请求体里面的数据;而RequestParam接收的是key-value
       里面的参数,所以它会被切面进行处理从而可以用普通元素、数组、集合、对象等接收)。
       即:如果参数时放在请求体中,传入后台的话,那么后台要用@RequestBody才能接收到;如果不是放在
              请求体中的话,那么后台接收前台传过来的参数时,要用@RequestParam来接收,或则形参前
              什么也不写也能接收。

注:如果参数前写了@RequestParam(xxx),那么前端必须有对应的xxx名字才行(不管其是否有值,当然可以通
       过设置该注解的required属性来调节是否必须传),如果没有xxx名的话,那么请求会出错,报400。

注:如果参数前不写@RequestParam(xxx)的话,那么就前端可以有可以没有对应的xxx名字才行,如果有xxx名
       的话,那么就会自动匹配;没有的话,请求也能正确发送。
       追注:这里与feign消费服务时不同;feign消费服务时,如果参数前什么也不写,那么会被默认是
                  @RequestBody的。
@RequestBody直接以String接收前端传过来的json数据:

@RequestBody以简单对象接收前端传过来的json数据:


ajax请求中的data : 若是经过 var data = JSON.stringify({"topicId":topicId}); 转义后的话 , Controller中入参需加上@RequestBody , 并且需要加上contentType: "application/json; charset=utf-8"; 

若是直接通过data:{"topicId":topicId} 发送请求 , Controller中入参不需要加上@RequestBody

======================================================================================

方式 3 : @RestController 注解 (此类里的所以方法返回值都是 Json)

拓展知识 当遇到 ajax 请求参数必须是Json 格式的话如下 :

前端 ajax :

data:JSON.stringify({'channelId':channelId}),
success:function(data){
alert(data.channelId);
},

contentType:'application/json;charset=utf-8'
后台 :

@RequestMapping(value="/login",produces="application/json;charset=UTF-8")
@ResponseBody public String test2() {

}

======================================================================================

posted @ 2020-05-25 14:03  Kaspar_Choo  阅读(1438)  评论(0编辑  收藏  举报