本节内容:
AJAX
- Asynchronous JavaScript and XML
- 异步的JavaScript与XML,不是一门新技术,只是一个新的术语。
- 使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面。
- 虽然X代表XML,但目前JSON的使用比XML更加普遍。
- https://developer.mozilla.org/zh-CN/docs/Web/Guide/AJAX
示例
- 使用jQuery发送AJAX请求。
实践
- 采用AJAX请求,实现发布帖子的功能。
封装Json工具
为了方便,我们先在CommunityUtil里封装几个json工具,使用阿里爸爸的fastjson,引入依赖。
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
//封装json工具
public static String getJSONString(int code, String msg, Map<String,Object> map){
JSONObject jsonObject=new JSONObject();
jsonObject.put("code",code);
jsonObject.put("msg",msg);
if(map != null){
for(String key : map.keySet()){
jsonObject.put(key,map.get(key));
}
}
return jsonObject.toJSONString();
}
//重载json工具
public static String getJSONString(int code, String msg){
return getJSONString(code,msg,null);
}
//重载json工具
public static String getJSONString(int code){
return getJSONString(code,null,null);
}
Ajax示例
在controller里写一个测试的方法。
//ajax示例
@RequestMapping(path = "/ajax",method = RequestMethod.POST)
@ResponseBody
public String testAjax(String name,