AJAX与JSON初次使用

简单介绍

在这次Java Web大作业中,用到了好多次AJAX,实现异步刷新网页,其中主要功能部分有评论、写文章、修改信息等。

下面简单说一说我是怎么使用的吧!

主要工具或是说环境

  • SSM
  • jQuery
  • fastjson

注意:

JSON返回时可能会出现乱码,需要设置一下:

1
2
@RequestMapping(value = "xxx", produces = "text/json;charset=UTF-8")
@ResponseBody

全局设置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=utf-8</value>
<value>application/x-www-form-urlencoded;charset=utf-8</value>
</list>
</property>
</bean>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

需求与实现

接着按照需求-实现这样的过程,展示我做了些什么吧!

查看某一类新闻

要求查看某一类新闻(国内、军事、科技。。。),点击类型后展示部分新闻,点击底部“查看更多”按钮,显示更多的这类新闻。

效果如下长截图,我设置的是每页10条新闻,若还有更多底部显示查看更多,若没有则显示没有更多内容。

某类新闻

前端完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>news</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/Static/js/lib/layUi/css/layui.css" media="all">
<script src="${pageContext.request.contextPath}/Static/js/lib/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
var css = {
marginLeft: 'auto',
marginRight: 'auto',
width: '70%',
height: 'auto',
};
$("#newsArea").css(css);
});

function more() {
$.ajax({
url: "${pageContext.request.contextPath}/queryNewsByCIdMore",
type: "post",
//注意序列化的值一定要放在最前面,并且不需要头部变量,不然获取的值得格式会有问题
data: {cid: ${cid}, cPage: $("#cp").val()},
dataType: "json",
success: function (data) {
$.each(data.moreNews, function (index, value) {
var s = '<div class="layui-card">' +
'<div class="layui-card-header">' +
'<a href="${pageContext.request.contextPath}/queryNewsById?nid=' + value.newsId +
'" target="_blank">' +
'<H2>' +
value.title +
'</H2>' +
'</a>' +
'</div>' +
'<div class="layui-card-body">' +
value.createTime +
'</div>' +
'</div>';
$("#newsbody").append(s);
});
if(data.cPage+1<${totalPage}){
var x='<a href="javascript:void(0);" onclick="more()">点击查看更多&gt;&gt;</a>';
$("#more").html(x)
}else{
var y='<p>没有更多内容了</p>';
$("#more").html(y)
}
$("#cp").val(data.cPage);
}
})
}
</script>
</head>
<body>
<div id="newsArea">
<div id="newsbody" style="margin-top: 20px">
<c:forEach items="${newsL}" var="news">
<div class="layui-card">
<div class="layui-card-header"><a
href="${pageContext.request.contextPath}/queryNewsById?nid=${news.newsId}"
target="_blank"><H2>${news.title}</H2></a></div>
<div class="layui-card-body">
<fmt:formatDate value="${news.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
</div>
</div>
</c:forEach>
</div>
<br/>
<div id="more">
<c:choose>
<c:when test="${cPage+1<totalPage}">
<a href="javascript:void(0);" onclick="more()">点击查看更多&gt;&gt;</a>
</c:when>
<c:otherwise>
<p>没有更多内容了</p>
</c:otherwise>
</c:choose>
</div>
</div>
<input id="cp" type="hidden" value="${cPage}"/>
</body>
</html>

对应Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@RequestMapping("queryNewsByCId")
public ModelAndView queryNewsByCid(@RequestParam("cid") long cid, @RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage) {
ModelAndView mv = new ModelAndView("front/news");
List<News> newsL = frontService.QueryNewsByCId(cid, cPage);
int total = frontService.QueryNewsTotalByCId(cid);
int totalPage = (int) Math.ceil(total * 1.0 / 10);
mv.addObject("cid", cid);
mv.addObject("cPage", cPage);
mv.addObject("totalPage", totalPage);
mv.addObject("newsL", newsL);
return mv;
}

@RequestMapping("queryNewsByCIdMore")
@ResponseBody
public String queryNewsByCIdMore(Model model, @RequestParam("cid") long cid, @RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage) {
Map<String, Object> map = new HashMap<String, Object>();
List<News> newsL = frontService.QueryNewsByCId(cid, (cPage + 1) * 10);
map.put("moreNews", newsL);
map.put("cPage", cPage + 1);
model.addAttribute("cPage", cPage + 1);
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
return JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
}

整个项目现在介绍不了,差很多东西,不过只看这部分AJAX与后台交互,还是可以的。

查看关键词新闻

这个与上面的查看某一类新闻几乎相同,不做过多介绍了,仅仅是把byCid的部分换成byKey。

Controller部分代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@RequestMapping("queryNewsByKey")
public ModelAndView queryNewsByKey(@RequestParam("key") String key, @RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage) {
ModelAndView mv = new ModelAndView("front/searchNews");
List<News> newsL = frontService.QueryNewsByKey(key, cPage);
int total = frontService.QueryNewsTotalByKey(key);
int totalPage = (int) Math.ceil(total * 1.0 / 10);
mv.addObject("key", key);
mv.addObject("cPage", cPage);
mv.addObject("totalPage", totalPage);
mv.addObject("newsL", newsL);
return mv;
}

@RequestMapping("queryNewsByKeyMore")
@ResponseBody
public String queryNewsByKeyMore(Model model, @RequestParam("key") String key, @RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage) {
Map<String, Object> map = new HashMap<>();
List<News> newsL = frontService.QueryNewsByKey(key, (cPage + 1) * 10);
map.put("moreNews", newsL);
map.put("cPage", cPage + 1);
model.addAttribute("cPage", cPage + 1);
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
return JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
}

新闻增删改

登录账户后,点击写文章,可以进到如下界面,其实是模仿简书的,左侧是已经写过的文章,点击标题转到文章详情,下方图标表示文章状态,若审核通过就是下图中绿色图标,若审核中则是黄色图标,若审核未通过则是红色图标。右下角有“修改”、“删除”按钮,修改需要通过AJAX,后端处理后返回JSON到前端,显示到左侧编辑区,提交修改,新闻重新变为审核中状态,删除则提示“确认删除?”,删除后从左侧移除该新闻,新建新闻则是提示成功新加新闻,并在左侧列表添加新内容。

edit

为防止未登录用户,或登录用户编辑他人的新闻,这里设置了一个特殊的a标签,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script type="text/javascript">
function toEdit() {
var myForm = document.createElement("form");
myForm.method = "post";
myForm.target = "_blank";
myForm.action = "${pageContext.request.contextPath}/toEdit";
var myInput = document.createElement("input");
myInput.setAttribute("name", "uid"); // 为input对象设置name
myInput.setAttribute("value", uid); // 为input对象设置value
myForm.appendChild(myInput);
document.body.appendChild(myForm);
myForm.submit();
document.body.removeChild(myForm); // 提交后移除创建的form
}
</script>

这样的a标签将get请求变为post请求,更加安全一些。

前端完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE html>
<html>
<head>
<title>edit</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/Static/js/lib/layUi/css/layui.css" media="all">
<style type="text/css">
html, body {
height: 100%;
}

body {
margin: 0;
}
</style>
<script src="${pageContext.request.contextPath}/Static/js/lib/jquery-3.5.1.min.js"></script>
<script src="${pageContext.request.contextPath}/Static/js/lib/ckEditor/ckeditor.js"></script>
<script type="text/javascript">
window.onload = function () {
CKEDITOR.replace('content', {height: "400px"});
};

$(function () {
$("#submit").click(function () {
var ops = $("#ops").val();
if (ops !== '0') {
opNews("updateNews");
} else {
opNews("addNews");
}
})
});

function delNews(nid) {
if (confirm("确定要删除吗?")) {
$.ajax({
url: "${pageContext.request.contextPath}/deleteNews",
type: "post",
//注意序列化的值一定要放在最前面,并且不需要头部变量,不然获取的值得格式会有问题
data: {nid: nid},
dataType: "json",
success: function (data) {
if (data.result === 'success') {
alert("新闻删除成功");
$("#div_" + nid).remove();
} else {
alert("新闻删除失败");
}
}
});
return true;
} else {
return false;
}
}

function upNews(nid) {
$.ajax({
url: "${pageContext.request.contextPath}/toUpdate",
type: "post",
//注意序列化的值一定要放在最前面,并且不需要头部变量,不然获取的值得格式会有问题
data: {nid: nid},
dataType: "json",
success: function (data) {
if (data.result === 'success') {
$("#ops").val(data.newsId);
var select = 'dd[lay-value=' + data.categoryId + ']';
//触发点击事件,实现自动选择
$("#categoryId").siblings("div.layui-form-select").find('dl').find(select).click();
$("#title").val(data.title);
CKEDITOR.instances.content.setData(data.content);
} else {
alert("出错!");
}
}
});
}

function opNews(op) {
var ops = $("#ops").val();
var uid = '${sessionScope.userS.userId}';
var cid = $("#categoryId").val();
var title = $("#title").val();
var content = CKEDITOR.instances.content.getData();
if (title !== "" && content !== "") {
if (ops !== '0') {
var dataparam = {
newsId: ops,
userId: uid,
categoryId: cid,
title: title,
content: content,
state: 0
}
} else {
var dataparam = {userId: uid, categoryId: cid, title: title, content: content, state: 0}
}
$.ajax({
url: "${pageContext.request.contextPath}/" + op,
type: "post",
//注意序列化的值一定要放在最前面,并且不需要头部变量,不然获取的值得格式会有问题
data: dataparam,
dataType: "json",
success: function (data) {
if (data.result === 'success') {
alert("发布成功,审核通过后点击左侧标题查看效果!");
var s = '<div class="layui-card" id="div_' + data.newsId + '">' +
'<div class="layui-card-header">' +
'<h3 style="max-width: 95%;overflow:hidden;white-space:nowrap; text-overflow:ellipsis" title="' + title + '">' +
'<a target="_blank" href="${pageContext.request.contextPath}/queryNewsById?nid=' + data.newsId + '">' + title + '</a>' +
'</h3>' +
'</div>' +
'<div class="layui-card-body">' +
'<img src="${pageContext.request.contextPath}/Static/img/inreview.png" class="layui-nav-img"/>' +
'<div align="right">' +
'<a href="javascript:void(0);" onclick="upNews(' + data.newsId + ')"><span style="color: blue">修改</span></a>' +
'<a href="javascript:void(0);" onclick="delNews(' + data.newsId + ')"><span style="color: red">删除</span></a>' +
'</div>' +
'</div>' +
'</div>';
if (ops !== '0') {
$("#div_" + nid).remove();
}
$("#newNews").prepend(s);
} else {
alert("发布失败!");
}
}
})
} else {
alert("标题或内容不能为空!");
}
}

function add() {
$("#ops").val('0');
var select = 'dd[lay-value=' + 1 + ']';
//触发点击事件,实现自动选择
$("#categoryId").siblings("div.layui-form-select").find('dl').find(select).click();
$("#title").val('');
CKEDITOR.instances.content.setData('');
}
</script>

</head>
<body>
<div style="height: 100%">
<div class="layui-row" style="height: 100%">
<div class="layui-col-xs3 layui-bg-gray" style="height: 100%;padding: 5px;overflow-y:auto;">
<div class="grid-demo">
<div style="background-color: #00FFFF; text-align: center;height: 50px">
<a href="${pageContext.request.contextPath}/User/toLogin" style="line-height: 50px"><img
src="${pageContext.request.contextPath}/Static/img/main.png"
class="layui-nav-img"/>首页</a>
</div>
<br/>
<div style="background-color:bisque; text-align: center;height: 50px">
<a href="javascript:void(0);" onclick="add()" style="line-height: 50px"><img
src="${pageContext.request.contextPath}/Static/img/addn.png"
class="layui-nav-img"/>新建</a>
</div>
<br/>
<div id="newNews">
</div>
<br/>
<div>
<c:forEach items="${ownNews}" var="news">
<div class="layui-card" id="div_${news.newsId}">
<div class="layui-card-header">
<h3 style="max-width: 95%;overflow:hidden;white-space:nowrap; text-overflow:ellipsis"
title="${news.title}">
<a target="_blank"
href="${pageContext.request.contextPath}/queryNewsById?nid=${news.newsId}">${news.title}</a>
</h3>
</div>
<div class="layui-card-body">
<c:choose>
<c:when test="${news.state==0}">
<img src="${pageContext.request.contextPath}/Static/img/inreview.png"
class="layui-nav-img"/>
</c:when>
<c:when test="${news.state==1}">
<img src="${pageContext.request.contextPath}/Static/img/accept.png"
class="layui-nav-img"/>
</c:when>
<c:otherwise>
<img src="${pageContext.request.contextPath}/Static/img/reject.png"
class="layui-nav-img"/>
</c:otherwise>
</c:choose>
<div align="right">
<a href="javascript:void(0);" onclick="upNews(${news.newsId})"><span
style="color: blue">修改</span></a>
<a href="javascript:void(0);" onclick="delNews(${news.newsId})"><span
style="color: red">删除</span></a>
</div>
</div>
</div>
</c:forEach>
</div>
</div>
</div>
<div class="layui-col-xs9">
<div class="layui-card">
<div class="layui-card-body" pad15="">
<div class="layui-form">
<div class="layui-form-item">
<label class="layui-form-label">标题</label>
<div class="layui-input-inline">
<input type="text" id="title" name="title"
placeholder="请输入标题" style="width: 400px"
class="layui-input"/>
</div>
<div class="layui-form-mid layui-word-aux"></div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">选择框</label>
<div class="layui-input-block">
<select id="categoryId" name="categoryId">
<c:forEach items="${categorys}" var="category">--%>
<option value="${category.category_id}">${category.category_name}</option>
</c:forEach>
</select>
<div class="layui-unselect layui-form-select">
<div class="layui-select-title">
<input type="text" placeholder="请选择" value="" readonly=""
class="layui-input layui-unselect">
<i class="layui-edge"></i></div>
<dl class="layui-anim layui-anim-upbit" style="">
<c:forEach items="${categorys}" var="category">--%>
<dd lay-value="${category.category_id}">${category.category_name}</dd>
</c:forEach>
</dl>
</div>
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">内容</label>
<div class="layui-input-block">
<textarea id="content" name="content"></textarea>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block" align="right">
<button type="reset" class="layui-btn layui-btn-primary">重新填写</button>
<button type="button" class="layui-btn" id="submit">发布</button>
<input type="hidden" id="ops" value="0"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="${pageContext.request.contextPath}/Static/js/lib/layUi/layui.js" charset="utf-8"></script>
<script>
layui.use('form', function () {
var form = layui.form; //只有执行了这一步,部分表单元素才会自动修饰成功
form.render();
});
</script>
</body>
</html>

Controller代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@RequestMapping("toEdit")
public ModelAndView toEdit(@RequestParam("uid") long uid) {
ModelAndView mv = new ModelAndView("front/edit");
mv.addObject("categorys", frontService.QueryAllCategorys());
mv.addObject("ownNews", frontService.QueryNewsByUId(uid));
return mv;
}

@RequestMapping("addNews")
@ResponseBody
public String addNews(News news) {
Map<String, Object> map = new HashMap<>();
int result = frontService.AddNews(news);
//添加新闻成功
if (result >= 0) {
//获取新闻ID
int LastId = 0;
LastId = Integer.parseInt(news.getNewsId().toString());
boolean flag = true;
PicNews picNews;
for (String pic_url : ImageUploadUtils.GetHtmlImageSrcList(news.getContent())) {
Pics pic = new Pics();
pic.setNewsId((long) LastId);
pic.setPicUrl(pic_url);
if (flag) {
picNews = new PicNews();
picNews.setNewsId((long) LastId);
picNews.setCategoryId(news.getCategoryId());
picNews.setTitle(news.getTitle());
picNews.setPicUrl(pic_url);
picNewsMapper.insertSelective(picNews);
flag = false;
}
frontService.AddPic(pic);
}
map.put("result", "success");
map.put("newsId", news.getNewsId());
} else {
map.put("result", "fail");
System.out.println("新闻增加失败");
}
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
return JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
}

@RequestMapping("toUpdate")
@ResponseBody
public String toUpdate(@RequestParam("nid") long nid) {
News news = frontService.QueryNewsById(nid);
Map<String, Object> map = new HashMap<>();
if (news != null) {
map.put("result", "success");
map.put("newsId", nid);
map.put("categoryId", news.getCategoryId());
map.put("title", news.getTitle());
map.put("content", news.getContent());
} else {
map.put("result", "fail");
}
return JSON.toJSONString(map);
}

@RequestMapping("updateNews")
@ResponseBody
public String updateNews(News news) {
Map<String, Object> map = new HashMap<>();
int result = frontService.UpdateNews(news);
if (result >= 0) {
map.put("result", "success");
map.put("newsId", news.getNewsId());
System.out.println("新闻修改成功");
} else {
map.put("result", "fail");
System.out.println("新闻修改失败");
}
return JSON.toJSONString(map);
}

@RequestMapping("deleteNews")
@ResponseBody
public String deleteNews(@RequestParam("nid") long nid) {
int result = frontService.DeleteNews(nid);
Map<String, Object> map = new HashMap<String, Object>();
if (result > 0) {
map.put("result", "success");
System.out.println("新闻删除成功");
} else {
map.put("result", "fail");
System.out.println("新闻删除失败");
}
return JSON.toJSONString(map);
}

我个人觉得这部分还是挺有趣的。

评论

这部分是最开始遇到的麻烦,正是因为这个才坚定了我要使用AJAX的决心。

需求就是简单的评论。

评论
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>show</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/Static/js/lib/layUi/css/layui.css" media="all">
<script src="${pageContext.request.contextPath}/Static/js/lib/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
var css = {
marginLeft: 'auto',
marginRight: 'auto',
width: '70%',
height: 'auto',
};
$("#show").css(css);
$("#sendTo").click(function () {
//获取值
var uid = '${sessionScope.userS.userId}';
var uname = '${sessionScope.userS.userName}';
var nid = '${news.newsId}';
var content = $("#content").val();
var uIcon = '${sessionScope.userS.userIcon}';
if (content !== "") {
$.ajax({
url: "${pageContext.request.contextPath}/addComment",
type: "post",
//注意序列化的值一定要放在最前面,并且不需要头部变量,不然获取的值得格式会有问题
data: {user_id: uid, news_id: nid, content: content},
dataType: "json",
success: function (data) {
if (data.result === 'success') {
alert("评论成功");
var iconSrc="${pageContext.request.contextPath}/Static/img/userIcon.png"
if("" !== uIcon){
iconSrc=uIcon;
}
$("#content").val('');
var s = '<div class="layui-card" id="div_' + data.cid + '">' +
'<div class="layui-card-body">' +
'<div align="left">' +
'<a href="${pageContext.request.contextPath}/queryUserById?uid='+uid+'">' +
'<img class="layui-nav-img" src="' + iconSrc + '"/>' +
uname + '</a>' +
' </div>' +
content +
'<div align="right">' +
'<a href="javascript:void(0);" onclick="delComment(' + data.cid + ')">删除</a>' +
'</div>' +
'<div align="right">' +
getCurrentDate(new Date()) +
'</div>' +
'</div>' +
'</div>';
$("#newComment").prepend(s);
} else {
alert("评论失败");
}
}
})
} else {
alert("评论不能为空!");
}
});
});

function delComment(cid) {
if (confirm("确定要删除吗?")) {
$.ajax({
url: "${pageContext.request.contextPath}/deleteComment",
type: "post",
//注意序列化的值一定要放在最前面,并且不需要头部变量,不然获取的值得格式会有问题
data: {cid: cid},
dataType: "json",
success: function (data) {
if (data.result === 'success') {
$("#div_" + cid).remove();
} else {
alert("评论删除失败");
}
}
});
return true;
} else {
return false;
}
}

function getCurrentDate(date) {
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
var str = y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + '-' + (h < 10 ? ('0' + h) : h) + ':' + (min < 10 ? ('0' + min) : min) + ':' + (s < 10 ? ('0' + s) : s);
return str;
}

function more() {
$.ajax({
url: "${pageContext.request.contextPath}/queryCommentByNIdMore",
type: "post",
//注意序列化的值一定要放在最前面,并且不需要头部变量,不然获取的值得格式会有问题
data: {nid: '${nid}', cPage: $("#cp").val()},
dataType: "json",
success: function (data) {
$.each(data.moreComments, function (index, value) {
if (value.user_id ===${sessionScope.userS.userId}) {
var z = '<div align="right">' +
'<a href="javascript:void(0);" onclick="delComment(' + value.comment_id + ')">删除</a>' +
'</div>';
} else {
var z = '';
}
var iconSrc="${pageContext.request.contextPath}/Static/img/userIcon.png"
if("user_icon" in value){
iconSrc=value.user_icon;
}
var s = '<div class="layui-card" id="div_' + value.comment_id + '">' +
'<div class="layui-card-body">' +
'<div align="left">' +
'<a href="${pageContext.request.contextPath}/queryUserById?uid=' + value.user_id + '"> ' +
'<img src="'+iconSrc+'" class="layui-nav-img"/>' +
value.user_name + '</a>' +
' </div>' +
value.content +
z +
'<div align="right">' +
value.createTime +
'</div>' +
'</div>' +
'</div>';
$("#comments").append(s);
});
if (data.cPage + 1 <${totalPage}) {
var x = '<a href="javascript:void(0);" onclick="more()">点击查看更多&gt;&gt;</a>';
$("#more").html(x)
} else {
var y = '<p>没有更多内容了</p>';
$("#more").html(y)
}
$("#cp").val(data.cPage);
}
})
}
</script>
</head>
<body bgcolor="F2F2F2">
<div align="left" style="margin-top: 10px;margin-left: 15px;">
<a href="${pageContext.request.contextPath}/User/toLogin" style="line-height: 50px"><img
src="${pageContext.request.contextPath}/Static/img/main.png"
class="layui-nav-img"/>首页</a>
</div>
<c:choose>
<c:when test="${news==null||news.state!=1}">
<h2 align="center">该文章审核尚未通过!</h2>
</c:when>
<c:otherwise>
<div id="show">
<div id="newsbody" style="margin-top: 20px">
<div class="layui-card">
<div class="layui-card-header"><h1>${requestScope.news.title}</h1></div>
<div align="right"><a
href="${pageContext.request.contextPath}/queryNewsByCId?cid=${news.categoryId}">其他新闻</a>
<fmt:formatDate value="${news.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
</div>

<div class="layui-card-body">
${requestScope.news.content}
<br/>作者:<a href="${pageContext.request.contextPath}/queryUserById?uid=${news.userId}">点这</a>
</div>
</div>
<br/>
</div>
<div>
评论区:<br/>
<c:choose>
<c:when test="${sessionScope.userS!=null}">
<div class="layui-card">
<div class="layui-card-body">
<form class="layui-form">
<div class="layui-input-block">
<textarea placeholder="请输入内容" class="layui-textarea" id="content"></textarea>
</div>
<div class="layui-input-block" align="right">
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
<button type="button" class="layui-btn" id="sendTo">评论</button>
</div>
</form>
</div>
</div>
</c:when>
<c:otherwise>
<a href="${pageContext.request.contextPath}/User/login">登陆后可评论</a>
</c:otherwise>
</c:choose>
<div id="newComment">
</div>
<br/>
<div id="comments">
<c:forEach items="${comments}" var="comment">
<div class="layui-card" id="div_${comment.comment_id}">
<div class="layui-card-body">
<div align="left">
<a href="${pageContext.request.contextPath}/queryUserById?uid=${comment.user_id}">
<c:choose>
<c:when test="${comment.user_icon==null}">
<img src="${pageContext.request.contextPath}/Static/img/userIcon.png"
class="layui-nav-img"/>
</c:when>
<c:otherwise>
<img src="${comment.user_icon}" class="layui-nav-img"/>
</c:otherwise>
</c:choose>
${comment.user_name}
</a>
</div>
${comment.content}
<div align="right">
<c:if test="${sessionScope.userS.userId==comment.user_id}">
<a href="javascript:void(0);" onclick="delComment(${comment.comment_id})">删除</a>
</c:if>
</div>
<div align="right">
${comment.createTime}
</div>
</div>
</div>
</c:forEach>
</div>
</div>
<br/>
<div id="more">
<c:choose>
<c:when test="${cPage+1<totalPage}">
<a href="javascript:void(0);" onclick="more()">点击查看更多&gt;&gt;</a>
</c:when>
<c:otherwise>
<p>没有更多内容了</p>
</c:otherwise>
</c:choose>
</div>
</div>
<input id="cp" type="hidden" value="${cPage}"/>
</c:otherwise>
</c:choose>
</body>
</html>

Contrller代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@RequestMapping("queryCommentByNIdMore")
@ResponseBody
public String queryCommentByNIdMore(@RequestParam("nid") long nid, @RequestParam(value = "cPage", required = false, defaultValue = "0") int cPage) {
Map<String, Object> map = new HashMap<>();
List<Comment> comments = frontService.QueryCommentsByNewsId(nid, (cPage + 1) * 3);
map.put("moreComments", comments);
map.put("cPage", cPage + 1);
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
return JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat);
}


@RequestMapping(value = "addComment", produces = "text/json;charset=UTF-8")
@ResponseBody
public String addComment(Comment comment) {
int result = frontService.AddComment(comment);
Map<String, Object> map = new HashMap<String, Object>();
if (result > 0) {
long LastId = comment.getComment_id();
map.put("result", "success");
map.put("cid", LastId);
System.out.println("评论成功");
} else {
map.put("result", "fail");
System.out.println("评论失败");
}
return JSON.toJSONString(map);
}

@RequestMapping(value = "deleteComment", produces = "text/json;charset=UTF-8")
@ResponseBody
public String deleteComment(@RequestParam("cid") long cid) {
int result = frontService.DeleteComment(cid);
Map<String, Object> map = new HashMap<String, Object>();
if (result > 0) {
map.put("result", "success");
System.out.println("评论删除成功");
} else {
map.put("result", "fail");
System.out.println("评论删除失败");
}
return JSON.toJSONString(map);
}

上面主要是三部分的AJAX的使用,其实还有一些,比如:用户信息修改、密码修改、反馈、用户头像上传,如果包括整个项目的话更多了。上面三个已经比较有代表性了。

总结

AJAX的使用能让用户得到不错的体验,不用动不动就刷新整个界面,搞得人很烦了。JSON只是一种数据格式,简单说就是键值对(key-value)的集合,可嵌套。在使用AJAX时,后端数据通常都是以JSON返回到前端的。这时只需要处理JSON数据即可,即完成了AJAX的使用。