2016-09-22 56 views
0

我正在構建一個網站,用戶可以喜歡,像按鈕正在工作,它正在數據庫中存儲喜歡。 我的問題是,我怎麼讓用戶,當他們再次點擊像按鈕,它會減去數據庫。 我有一個類似按鈕的動畫,第一個默認狀態是灰色的,然後當用戶點擊它時,它會變成藍色,並且會出現一個「喜歡」的文字。那麼當用戶再次點擊時,它會回到黑色。像按鈕一樣,在數據庫上加減。 nodejs,mongodb,mongoose,jquery

這是我在POST航線代碼(因爲我是將數據添加到數據庫)

app.post("/index/:id", function(req,res){ 
    TestData.findById(req.params.id, function(err, theUser){ 
     if(err){ 
      console.log(err); 
     } else { 
      theUser.likes += 1; 
      theUser.save(); 
      console.log(theUser.likes); 
     } 
    }); 
}); 

我EJS文件:

 <a class="likeicon" href="/index/<%= newUsers._id %>?_method=POST"> 
     <i class="fa fa-thumbs-o-up" aria-hidden="true" ></i> 
     </a> 

和我的jQuery:

$(".likeicon").on('click', function(){ 
if($(this).css("color") === "rgb(0, 0, 255)"){ 
    $("#likedtxt").remove(); 
    $(this).css("color", "black"); 
    $(this).animate({fontSize: "15px"}); 


} else { 
    $(this).css("color", "blue"); 
    $(this).append("<span id='likedtxt'>Liked</span>"); 
    $(this).animate({fontSize: "18px"}); 
} 
}); 

也是另問題,當我點擊喜歡,它正在添加到數據庫,但我怎麼能顯示它活在用戶屏幕上,計數喜歡s是否更新?無需重新加載屏幕。因爲我不想使用res.redirect,它會刷新網頁。

回答

1

伊莫你可以更好的onclick寫功能爲 「likeicon」 按鈕

<a class="likeicon" userId="<%= newUsers._id %>" onclink="updateLikes()"> 
    <i class="fa fa-thumbs-o-up" aria-hidden="true" > 49 </i> 
</a> 

功能:

function updateLikes() { 
    id = $('.likeicon').attr('userId'); 
    $.post('/index/' + id, function (response) { 
     $('fa-thumbs-o-up').text(response.likeCount); //your counter on a page 
     //and update likes counter with response 
    }) 
} 

而且Node.js的

app.post("/index/:id", function (req, res) { 
    TestData.findById(req.params.id, function (err, theUser) { 
     if (err) { 
      console.log(err); 
     } else { 
      theUser.likes += 1; 
      theUser.save(); 
      console.log(theUser.likes); 
      res.send({likeCount: theUser.likes}); //something like this... 
     } 
    }); 
}); 
+0

'res.send('發送一些數據');'你想從這個地方發送什麼?我當然不'theuser.likes'。 – SkyQ

+0

哦,我的壞。我想「也是另一個問題,當我點擊喜歡,它正在添加到數據庫,但我怎麼能顯示它現場」只爲一個用戶,誰點擊... Idk然後如何更新喜歡所有用戶 – BlackRockSoul

+0

傢伙,有沒有一種方式,例如,當我更新數據庫上的數據時,它也會在網頁上更新LIVE?而無需重新加載網頁?因爲如果我把「res.redirect(」back「)這樣的東西放回到網頁,刷新並且用戶看到更新的類似計數。但我不想刷新我的網頁。 – John

0

有關更新計數喜歡你應該送更新從服務器的喜歡計數:

app.post("/index/:id", function(req,res){ 
    TestData.findById(req.params.id, function(err, theUser){ 
     if(err){ 
      console.log(err); 
      return res.status(500).send('Something went wrong!'); // You should notify user about any error  
     } else { 
      theUser.likes += 1; 
      theUser.save(function(err){ 
      if(err) return res.status(500).send('Something went wrong!'); 
      return res.send({likes_count: theUser.likes}); 
      }); 

     } 
    }); 
}); 
+0

在我的網站上,有圖片和每一張照片的評論和數量。每當我喜歡這張照片時,喜歡的人數都應該更新LIVE,而無需重新加載網站。所以「res.send()」不會。你知道一種方式,我不能更新像REALTIME一樣的計數? – John

+0

讓我們安排它。如果我喜歡圖片,那麼喜歡的數量應該爲我和任何用戶更新,無需重新加載。對? 如果是的話,你可以使用socket等。 http://socket.io/ – SkyQ

+0

是的,這是正確的。謝謝! – John