不刷新页面添加评论
程序员文章站
2022-04-11 17:27:02
...
function addmycomment(movieid) {
var myDate = new Date();//获取系统当前时间
var year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
var month = myDate.getMonth()+1; //获取当前月份(0-11,0代表1月)
var day = myDate.getDate(); //获取当前日(1-31)
var hours = myDate.getHours(); //获取当前小时数(0-23)
var min = myDate.getMinutes(); //获取当前分钟数(0-59)
var sec = myDate.getSeconds(); //获取当前秒数(0-59)
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
if (hours < 10) {
hours = "0" + hours;
}
if (min < 10) {
min = "0" + min;
}
if (sec < 10) {
sec = "0" + sec;
}
var mytime = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
var maincomments = $("textarea").val();
var appendcontent = "<div class='col-md-12 user'><span class='username'>addmin</span><span class='commentstime'>"+mytime+"</span></div><div class='col-md-12 contents'>"+maincomments+"</div><%-- <c:forEach items='' var=''> --%><div class='col-md-12 replaycontents'></div><%-- </c:forEach> --%><div class='col-md-12 replaybutton'><input type='button' value='回复' /></div>";
if (maincomments != null && maincomments != "") {
$.ajax({
url: "/LearnJAVAwithXge01/addmaincomment",
type: "post",
dataType: "json",
data: {"movieid":movieid,"maincomments":maincomments},
success: function(result){
if (result) {
$("#commentscontent").append(appendcontent);
$("textarea").val("");
} else {
layer.alert("发表失败!",{title:"提示"});
}
},
error: function(){
layer.alert("错误!",{title:"提示"});
}
});
} else {
layer.alert("发表内容不能为空!",{title:"提示"});
}
}
首先将评论内容添加到数据库,添加成功后,再将评论的内容追加到评论区域
另一种方法是使用JS动态加载:设置setInterval(),每过多久执行一次后台查询评论的方法,后台json返回一个评论集合,然后前端动态生成评论模板和数据,在使用.html()在加载内容添加到评论区域