var jsonObject = new Object(); jsonObject.name = "jack"; jsonObject.phone = "13879013334"; jsonObject.id = "asdghj"; $.ajax({ type:"POST", url: "${pageContext.request.contextPath}/ajax", //contentType: "application/json", //用servlet獲取 不需要寫(xiě)這個(gè) 因?yàn)閷?xiě)了post類型,默認(rèn)application/x-www-form-urlencoded dataType: "json", //服務(wù)器返回的數(shù)據(jù)類型??梢詫?xiě)json,也可以寫(xiě)text 有時(shí)候后臺(tái)發(fā)過(guò)來(lái)的json格式字符串會(huì)有問(wèn)題,如BOM頭,用json會(huì)拿不到數(shù)據(jù),需要用text來(lái)測(cè)試 data: jsonObject, //發(fā)送到服務(wù)器的參數(shù),直接用json對(duì)象。因?yàn)?span style="background-color: rgb(242, 242, 245);">contentType沒(méi)有用"application/json"就不需要用JSON.stringify(jsonObject)轉(zhuǎn)字符串, success: function (data) { console.log(data) }, error: function (data){ alert("解析數(shù)據(jù)失??!"); } });
解讀: 客戶端提交的contentType只能為application/x-www-form-urlencoded或者multipart/form-data,二進(jìn)制數(shù)據(jù)使用多重編碼。前面默認(rèn)編碼,即字符串,后者為文件。但如果從服務(wù)器下載的話編碼就很多了,比如你說(shuō)的application/json,text/plan,application/image.....等都可以。
用springmvc的注解@RequestBody Map<String, String> params 可以接收到用ajax發(fā)來(lái)的參數(shù).
前臺(tái)代碼 $.ajax({ type : "POST", url : url, data : data, dataType : "JSON", contentType:"application/json", success : function(result) { alert(result); } });
后臺(tái)代碼 @RequestMapping(value = "/sk/api/params", method = RequestMethod.POST) public void params(@RequestBody Map<String, String> params, HttpServletRequest request, HttpServletResponse response) {
System.out.println("總共獲取到:"+params.size()+"個(gè)參數(shù)"); for(String key : params.keySet()){ System.out.println(key + " : " + params.get(key)); } writeJson(response, "ok"); }
不用框架,前端request的contentType是application/json的話,這樣獲取
StringBuffer json = new StringBuffer(); BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { json.append(line); //若前端發(fā)送的是json格式字符串,即用JSON.stringify(obj)轉(zhuǎn)換, 拿到的是{"name":"jack","phone":"13879013334","id":"asdghj"} //若前端發(fā)送的是json對(duì)象,拿到的是name=jack&phone=13879013334&id=asdghj return json.toString();
|