Node写博客--内容评论和分页实现

1.首先在view.html中增加评论区域

 

2.使用ajax方法,把评论提交上去,在api.js中写入

var Content=require('../models/Content');//引入内容


//评论提交
router.post('/comment/post',function (req,res) {
    //内容的id
    var contentId = req.body.contentid ||'';
    var postData={
        username:req.userInfo.username,
        postTime:new Date(),
        content:req.body.content
    };
    //查询当前这篇内容的信息
    Content.findOne({
        _id:contentId
    }).then(function (content) {
        content.comments.push(postData);
        return content.save();
    }).then(function (newContent) {
        responseData.message='评论成功';
        responseData.data=newContent;
        res.json(responseData);
    });
});

3.将每一篇的评论保存在每篇评论下面,在contents.js中加入下面代码

//评论
    comments:{
        type:Array,
        default:[]
    }

4.根据后台修改前台,增加comment.js使用ajax传输数据

//提交评论
$('#messageBtn').on('click',function () {
    $.ajax({
        type:'POST',
        url:'/api/comment/post',
        data:{
            contentid:$('#contentId').val(),
            content:$('#messageContent').val()
        },
        success:function (responseData) {
            $('#messageContent').val('');
        }
    });
});

function renderComment(comments) {
    var html='';
    for(var i=0;i<comments.length;i++){
        html+='<div class="messageBox">'+
                '<p class="name clear"><span class="fl">'+comments[i].username+'</span>' +
                '<span class="fr">'+comments[i].postTime+'</span></p>' +
                '<p>'+comments[i].content+'</p>'+
                '</div>';
    }
    $('.messageList').html(html);
}

5.但是在页面刷新的时候,能展示出评论,在api.js中修改

//获得指定文章的所有评论

router.get('/comment',function (req,res) {
//内容的id
    var contentId = req.query.contentid ||'';
    Content.findOne({
        _id:contentId
    }).then(function (content) {
        responseData.data=content.comments;
        res.json(responseData);
    });
});

在comment.js中修改

//提交评论
$('#messageBtn').on('click',function () {
    $.ajax({
        type:'POST',
        url:'/api/comment/post',
        data:{
            contentid:$('#contentId').val(),
            content:$('#messageContent').val()
        },
        success:function (responseData) {
            $('#messageContent').val('');
            //得到当前最新的评论
            renderComment(responseData.data.comments.reverse());
        }
    });
});

//每次页面重载的时候获取一下该文章的所有评论
$.ajax({
    url:'/api/comment',
    data:{
        contentid:$('#contentId').val()
    },
    success:function (responseData) {
        renderComment(responseData.data.reverse());
    }
});

function renderComment(comments) {
    var html='';
    for(var i=0;i<comments.length;i++){
        html+='<div class="messageBox">'+
                '<p class="name clear"><span class="fl">'+comments[i].username+'</span>' +
                '<span class="fr">'+comments[i].postTime+'</span></p>' +
                '<p>'+comments[i].content+'</p>'+
                '</div>';
    }
    $('.messageList').html(html);
}

6.问题:评论数和时间问题

(1)在function renderComment中加入

$('#messageCount').html(comments.length);

(2)在comment.js中格式化时间

//格式化时间
function formatDate(d) {
    var date1=new Date(d);
    return date1.getFullYear()+'年'+(date1.getMonth()+1)+'月'+date1.getDate()+'日 '+date1.getHours()+':'+date1.getMinutes()+':'+date1.getSeconds();
}

7.前端对评论区进行分页

var perpage=5;//每页显示多少条
var page=1;
var pages=0;
var comments=[];



//提交评论
$('#messageBtn').on('click',function () {
    $.ajax({
        type:'POST',
        url:'/api/comment/post',
        data:{
            contentid:$('#contentId').val(),
            content:$('#messageContent').val()
        },
        success:function (responseData) {
            $('#messageContent').val('');
            comments=responseData.data.comments.reverse();
            //得到当前最新的评论
            renderComment();
        }
    });
});

//每次页面重载的时候获取一下该文章的所有评论
$.ajax({
    url:'/api/comment',
    data:{
        contentid:$('#contentId').val()
    },
    success:function (responseData) {
        comments=responseData.data.reverse();
        renderComment();
    }
});
$('.pager').delegate('a','click',function () {
    if($(this).parent().hasClass('previous')){
        page--;
    }else {
        page++;
    }
    renderComment();
});



function renderComment() {

    $('#messageCount').html(comments.length);
    var pages=Math.ceil(comments.length/perpage);
    var $lis=$('.pager li');
    $lis.eq(1).html(page +'/'+pages);
    var start=Math.max(0,(page-1)*perpage);
    var end=Math.min(start+perpage,comments.length);

    if(page<=1){
        page=1;
        $lis.eq(0).html('<span>没有上一页</span>');
    }else {
        $lis.eq(0).html('<a href="javascript:;">上一页</a>');
    }
    if(page>=pages){
        page=pages;
        $lis.eq(2).html('<span>没有下一页了</span>');
    }else {
        $lis.eq(2).html('<a href="javascript:;">下一页</a>');
    }
    var html='';
    for(var i=start;i<end;i++){
        html+='<div class="messageBox">'+
                '<p class="name clear"><span class="fl">'+comments[i].username+'</span>' +
                '<span class="fr">'+formatDate(comments[i].postTime)+'</span></p>' +
                '<p>'+comments[i].content+'</p>'+
                '</div>';
    }
    $('.messageList').html(html);
}
//格式化时间
function formatDate(d) {
    var date1=new Date(d);
    return date1.getFullYear()+'年'+(date1.getMonth()+1)+'月'+date1.getDate()+'日 '+date1.getHours()+':'+date1.getMinutes()+':'+date1.getSeconds();
}

8.分类页中的评论数

9.细节处理

(1)内容的显示,多样化(百度编辑器)

(2)对安全的处理xss等等

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 数据库查询分页 首先需要在后端通过数据库查询获取到所有数据,然后再根据前端传来的分页参数进行分页处理,最后将分页后的数据返回给前端。 例如使用MySQL数据库,在Node.js中可以使用mysql模块连接数据库,然后通过LIMIT和OFFSET关键字进行分页查询。 ``` const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'test' }); // 获取总记录数 function getCount(callback) { const sql = 'SELECT COUNT(*) AS total FROM table_name'; connection.query(sql, (error, results) => { if (error) throw error; callback(results[0].total); }); } // 分页查询 function getList(pageNum, pageSize, callback) { const offset = (pageNum - 1) * pageSize; const sql = `SELECT * FROM table_name LIMIT ${pageSize} OFFSET ${offset}`; connection.query(sql, (error, results) => { if (error) throw error; callback(results); }); } ``` 2. 前端分页 前端分页是指在前端将所有数据加载完毕后,通过JS来进行分页处理,最终将分页后的数据呈现在页面上。 例如使用Vue.js,可以在组件中定义一个列表,然后使用computed属性计算分页数据。 ``` <template> <div> <table> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr v-for="item in paginatedList" :key="item.id"> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td>{{ item.age }}</td> </tr> </tbody> </table> <div> <button @click="prevPage">上一页</button> <span>{{ currentPage }} / {{ pageCount }}</span> <button @click="nextPage">下一页</button> </div> </div> </template> <script> export default { data() { return { list: [], // 所有数据 pageSize: 10, // 每页显示条数 currentPage: 1 // 当前页码 }; }, computed: { pageCount() { return Math.ceil(this.list.length / this.pageSize); // 总页数 }, paginatedList() { const startIndex = (this.currentPage - 1) * this.pageSize; const endIndex = startIndex + this.pageSize; return this.list.slice(startIndex, endIndex); // 分页后的数据 } }, methods: { prevPage() { if (this.currentPage > 1) { this.currentPage--; } }, nextPage() { if (this.currentPage < this.pageCount) { this.currentPage++; } } }, mounted() { // 获取所有数据 // ... } }; </script> ``` 需要注意的是,前端分页虽然不需要进行数据库分页查询,但是在数据量较大时仍然会存在性能问题。因此,建议在数据量较大时使用后端分页查询方式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值