前台代碼:
function channel(){ //先獲取選中的值 var channelId = $("#channelId option:selected").val(); //來判斷發送的鏈接 if(channelId ==2){ **需要注意地方 start** var schoolBannerInfo = { "img": channelId, "title": channelId, "info": channelId, "channelId": channelId }; **需要注意地方 end** $.ajax({ url:"ceshijson", type:"post", dataType:'json', **需要注意地方 start** contentType:'application/json;charset=utf-8', data:JSON.stringify(schoolBannerInfo), **需要注意地方 end** success:function(data){ alert(data); }, error:function(XMLHttpRequest, textStatus, errorThrown){ alert("Error") alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); } }
加粗的部分是要注意的地方。
其中contentType:’application/json;charset=utf-8’不能省掉,否則會報415錯誤。
畢竟我發送的是json字符串,得告訴服務器,來的數據是json數據。
JSON.stringify()是將JavaScript對象轉換為json字符串
JSON.parse(jsonstr)是將json字符串轉換為JavaScript對象
補充知識:json其實就是JavaScript的子集。
參考地址:http://www.jb51.net/article/35090.htm
后台代碼:
pojo類:
public class SchoolBannerInfo { private Integer id; private Date createTime; private String img; private String title; private String info; private Integer seq; private Integer schoolId; private String type; private boolean enable; private String link; private String channelId; }
get與set方法自己生成,這個就不貼出來了。
controller中方法:
@RequestMapping(value="/ceshijson",produces="application/json;charset=UTF-8") @ResponseBody public SchoolBannerInfo ceshijson(@RequestBody SchoolBannerInfo schoolBannerInfo) throws IOException{ // Map<String,Object> map = new HashMap<String,Object>(); // map.put("channelId", channelId); // ObjectMapper mapper = new ObjectMapper(); // channelId = mapper.writeValueAsString(map); return schoolBannerInfo; }
注意:
1、@RequestBody不能省,因為前台發過來的數據是json數據,得用這個注解去解析該怎么接收這些數據給pojo類的對象。
2、因為我也要返回json數據。所以需要這個注解@ResponseBody,把Java對象轉換成json字符串
3、當使用@RequestBody時,要求前台傳過來的數據是json字符串。如果是json對象是會出錯的。所以如果你前台data部分這么寫:data:{“channelId”:2},這樣是不行的。因為{“channelId”:2}是json對象,你需要再在外層加個引號’{“channelId”:2}’這樣才行。