案例效果如图
![图片[1]-ajax实现发表评论案例 - it同学-it同学](https://www.ittx.cn/wp-content/uploads/2021/08/屏幕截图-2021-08-24-152502-1024x611.jpg)
js部分
function getCommentList() {
$.ajax({
method: 'get',
url: 'http://www.liulongbin.top:3006/api/cmtlist',
success: function(res) {
if (res.status !== 200) {
return alert('获取评论失败!')
}
var rows = [];
$.each(res.data, function(i, item) {
rows.push('<li class="list-group-item"><span class="badge" style="background-color: rgb(67, 136, 113);">评论时间:' + item.time + '</span><span class="badge" style="background-color: rgb(138, 97, 46);">评论人:' + item.username + '</span> ' + item.content + '</li>')
})
$('#coms').empty().append(rows.join(''));
}
})
}
getCommentList();
$(function() {
$('#formAddCmt').on('submit', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('http://www.liulongbin.top:3006/api/addcmt', data, function(res) {
if (res.status !== 201) {
return alert('发表评论失败!')
}
getCommentList();
$('#formAddCmt')[0].reset();
})
})
})
在线演示
接口由黑马程序员提供
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持一下吧