发布帖子
AJAX
Asynchronous JavaScript and XML
异步的JavaScript 与 XML,不是一门新技术,只是一个新的术语。
异步请求:当前网页不刷新,访问服务器,服务器会返回结果,通过返回结果,对网页进行处理(刷新,更改样式);
使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面。
示例
使用jQuery发送AJAX请求。
在AlphaController
// ajax示例
CommunityUtil
//ajax示例
public static String getJSONString(int code, String msg, Map<String,Object> map){
JSONObject json= new JSONObject();
json.put("code",code);
json.put("msg",msg);
if (map != null){
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);
}
//测试json 能够实现前后端交互
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));
}
新建ajax-demo.html静态页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX发送帖子</title>
</head>
<body>
<p>
<!-- 点击请求,触发单击事件-->
<input type="button" value="发送" onclick="send();">
</p>
<!-- 引入jquery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script>
<!-- 声明send方法-->
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);
}
);
}
</script>
</body>
</html>
测试结果
实践
采用AJAX请求,实现发布帖子的功能
在DiscussPostMapper里增加帖子方法
//增加帖子方法
int insertDiscussPost(DiscussPost discussPost);
在discusspost-mapper里写sql语句
<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>
DiscussPostService
DiscussPostController
//帖子
在index.js里写入点击事件
var CONTEXT_PATH="/community";
$(function(){
$("#publishBtn").click(publish);
});
function publish() {
$("#publishModal").modal("hide");
// 获取标题和内容
var title = $("#recipient-name").val();
var content = $("#message-text").val();
// 发送异步请求(POST)
$.post(
CONTEXT_PATH + "/discuss/add",
{"title":title,"content":content},
function(data) {
data = $.parseJSON(data);
// 在提示框中显示返回消息
$("#hintBody").text(data.msg);
// 显示提示框
$("#hintModal").modal("show");
// 2秒后,自动隐藏提示框
setTimeout(function(){
$("#hintModal").modal("hide");
// 刷新页面
if(data.code == 0) {
window.location.reload();
}
}, 2000);
}
);
}
测试结果