如何仅在特定事件之后加载服务器variables?
我需要两个服务器variables只能在db中的var变化之后加载。
现在,它们在加载页面时立即加载,因此保持事件之前的值( upvotesRef.transaction
)。
$('.HP').text("<%= post.upvotes - post.downvotes %> HP");
码:
$('.UpvoteButton').click(function () { var $this = $(this); if ($this.hasClass("on")) { $this.removeClass("on"); upvotesRef.transaction(function (upvotes) { if (!upvotes) { upvotes = 0; } upvotes = upvotes - 1; return upvotes; }); userRef.remove(); $('.HP').text("<%= post.upvotes - post.downvotes %> HP");
编辑:
我最终创build了局部variables来解决我的问题。 谢谢您的回答 !
var upvotesLocal = <%= post.upvotes %>; var downvotesLocal = <%= post.downvotes %>; $('.UpvoteButton').click(function () { var $this = $(this); if ($this.hasClass("on")) { $this.removeClass("on"); upvotesRef.transaction(function (upvotes) { if (!upvotes) { upvotes = 0; } upvotes = upvotes - 1; return upvotes; }); upvotesLocal = upvotesLocal -1 userRef.remove(); $('.HP').text((upvotesLocal - downvotesLocal) + " HP")
你应该得到并更新交易后的variables权利?
这意味着它应该发生在你的callback。
我假设你正在使用firebase事务方法。
那么你的callback应该是第二个参数:
$('.UpvoteButton').click(function () { var $this = $(this); if ($this.hasClass("on")) { $this.removeClass("on"); upvotesRef.transaction(function (upvotes) { if (!upvotes) { upvotes = 0; } upvotes = upvotes - 1; return upvotes; }, updateVotes); //<-- here the callback function added userRef.remove(); function updateVotes(error, isCommitted, upvotes) { //here you got already your new upvotes //but you should request the downvotes, //here you need the ajax request, see eg Dez's answer or comments }
考虑到我在node.js中没有经验,你应该做的是取代$('.HP').text("<%= post.upvotes - post.downvotes %> HP");
在AJAX调用中获得更新的variables并将其添加到jQuery中。 沿着这些线路的东西:
$('.UpvoteButton').click(function () { var $this = $(this); if ($this.hasClass("on")) { $this.removeClass("on"); upvotesRef.transaction(function (upvotes) { if (!upvotes) { upvotes = 0; } upvotes = upvotes - 1; return upvotes; }); $.ajax({ type : 'POST', data: { userRef: userRef}, contentType: 'application/json', url: 'http://localhost:3000/endpoint', success: function(data) { console.log('success'); console.log(JSON.stringify(data)); /* Do whatever you need with your data, for example*/ $('.HP').text(data.upvotes + "-" + data.downvotes + "HP"); }, error : function (event) { console.log(event); } }); userRef.remove(); ... }
在node.js
一边,你将需要沿着这些线:
app.post('/endpoint', function(req, res) { console.log(req.body.userRef) /* Get the upvotes and downvotes and send them back in the response */ res.contentType('json'); res.send({ some: JSON.stringify({response:'json'}) }); });
我很抱歉没有能够显示一个确切的function答案。