如何使用jquery自动刷新特定div并经常向客户端发送数据

时间:2018-06-17 07:57:27

标签: jquery node.js ajax mongodb

我一直在尝试在我的网站上创建一个类似的按钮。当用户点击它时,它会增加计数器并发布到服务器并更新db.But我试图自动刷新显示no的字段喜欢每500毫秒使用jquery.But无法确定如何做到这一点,并在制作ajax get请求后,我如何发送不喜欢count到index.pug文件,其中输入字段存在。我将提交我试过的代码。请通过改变和建议来帮助我解决这个问题。提前谢谢。

  1. index.pug

    extends layout
    
    block content
    
      h1 #{title}   ul.list-group
        >     each post, i in posts
        >       li.list-group-item
        >         a(href="/forum/"+post._id+"?"+post.author)= post.title
        >         div #{post.body}
        >         button(id="likeicon" value=post._id)  LIKE
        >         input.form-control(name='likes', type='text')
    
  2. main.js(我的jquery代码所在的位置)

      $('#likeicon').on('click',() => {
            var id = $('#likeicon').val();
            $.ajax({
              url:'/forum/addlikes/'+id,
              method:"POST"
            })
          })
    
          refresh(id);
    
        });
    
        function refresh(id){
          setInterval(() => {
            $.ajax({
              url:'/forum/getlikes'+id,
              method:"GET"
            })
          },500)
        }
    

    3.route部分为这个特殊的功能

    router.get('/getlikes/:id',(req,res) =>{
      Post.findById(req.params.id,(err,post) => {
        res.render('index.pug',{post:post})
    });
    });
    
    router.post('/addlikes/:id',(req,res) => {
      Post.findById(req.params.id,(err,post) => {
        if(err) throw err;
        else{
          post.likes+=1;
          post.save((err) =>{
            if(err) throw err;
            else{
              console.log(post.likes);
            }
          });
        }
      });
    
    });
    

0 个答案:

没有答案