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() {

}

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM