- AJAX(异步请求,当前网页不刷新时访问服务器)
- Asynchronous JavaScript and XML
- 异步的JavaScript与XML,不是一门新技术,只是一个新的术语。
- 使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面。
- 虽然X代表XML,但目前JSON的使用比XML更加普遍。(XML不好解析)
- https://developer.mozilla.org/zh-CN/docs/Web/Guide/AJAX。
- 示例
- 使用jQuery(js框架,更方便)发送AJAX请求。
- 实践
- 采用AJAX请求,实现发布帖子的功能。
- 引入新的FastJson依赖包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.14</version>
</dependency>
- 开发工具方法处理json数据
- 返回编码
- 返回提示信息
- 返回业务数据
CommunityUtils里面
public static String getJSONString(int code, String msg, Map<String, Object> map) {
//fastjson API
JSONObject json = new JSONObject();
json.put("code", code);
json.put("msg", msg);
if (map != null) {//遍历map.存入json对象
for (String key : map.keySet()) {
json.put(key, map.get(key));
}
}
return json.toJSONString();
}
//重载函数,应对不同的业务情况
public static String getJSONString(int code, String msg) {
return getJSONString(code, msg, null);
}
public static String getJSONString(int code) {
return getJSONString(code, null, null);
}
//进行测试
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("name", "zhangsan");
map.put("age", 25);
System.out.println(getJSONString(0, "ok", map));
}
- json发布异步请求的示例
//ajax示例
@RequestMapping(path = "/ajax",method = RequestMethod.POST)
@ResponseBody//异步请求,返回字符串
public String testAjax(String name,int age){//浏览器提交的数据name,age
System.out.println(name);
System.out.println(age);
return CommunityUtil.getJSONString(0,"操作成功");
}
ajax页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
</head>
<body>
<p>
<input type="button" value="发送" onclick="send();">
</p>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script>
function send(){
$.post(
"/community/alpha/ajax",
{"name":"张三","age":23},
function (data){
console.log(typeof (data));
console.log(data);
data=$.parseJSON(data);
console.log(typeof (data));
console.log(data.code);
console.log(data.msg);
}<!--匿名函数,调用页面,浏览器获得响应后会访问此方法,将服务器返回的数据传给data,回调函数-->
);
}
</script>
</body>
</html>
页面无刷新,但访问了服务器
正式编写发布帖子的功能
- DiscussPostMapper.java中追加方法
int insertDiscussPost(DiscussPost discussPost);//发布帖子
- discusspost-mapper.xml中追加方法
<sql id="insertFields">
user_id, title, content, type, status, create_time, comment_count, score
</sql>
<insert id="insertDiscussPost" parameterType="DiscussPost">
insert into discuss_post(<include refid="insertFields"></include>)
values(#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})
</insert>
3.在服务层写代码
DiscussPostService.java
@Autowired
private SensitiveFilter sensitiveFilter;
public int addDiscussPost(DiscussPost post) {
if (post == null) {
throw new IllegalArgumentException("参数不能为空!");
}
// 转义HTML标记,将标签”<>“等处理
post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));//springMVC提供的工具
post.setContent(HtmlUtils.htmlEscape(post.getContent()));
// 过滤敏感词
post.setTitle(sensitiveFilter.filter(post.getTitle()));//只有title,contents需要过滤关键词
post.setContent(sensitiveFilter.filter(post.getContent()));
return discussPostMapper.insertDiscussPost(post);
}
- 视图层(controller、html)
DiscussPostController.java
package com.nowcoder.community.controller;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
@Controller
@RequestMapping("/discuss")
public class DiscussPostController {
@Autowired
private DiscussPostService discussPostService;
@Autowired
private HostHolder hostHolder;//获取当前用户
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ResponseBody//返回给浏览器一个字符串
public String addDiscussPost(String title, String content) {//String title, String content页面闯入的值
User user = hostHolder.getUser();
if (user == null) {
return CommunityUtil.getJSONString(403, "你还没有登录哦!");//403没有权限
}
//创建一个帖子对象
DiscussPost post = new DiscussPost();
post.setUserId(user.getId());
post.setTitle(title);
post.setContent(content);
post.setCreateTime(new Date());
discussPostService.addDiscussPost(post);
// 报错的情况,将来统一处理.
return CommunityUtil.getJSONString(0, "发布成功!");//给浏览器一个信息发布成功
}
}
- 处理页面index.html
$(function(){
$("#publishBtn").click(publish);
});
function publish() {
$("#publishModal").modal("hide");//将输入帖子框先隐藏框
//服务器获取标题和内容
var title=$("#recipient-name").val();//jqueryID选择器,选中文本框得到文本框内的值
var content =$("#message-text").val();
//发送异步请求
$.post(
CONTEXT_PATH+"/discuss/add",
{"title":title,"content":content},
function(data){
data=$.parseJSON(data);
//在提示框中显示返回消息
$("#hintModal").text(data.msg);
//显示提示框
$("#hintModal").modal("show");
//2秒后自动隐藏提示框
setTimeout(function(){
$("#hintModal").modal("hide");
//刷新页面,判断是否发布成功
if(data.code==0){
window.location.reload();
}
}, 2000);
}
);
}