【发布时间】:2017-03-17 11:27:07
【问题描述】:
问题:
我在脚本标签中有一些 Firebase 代码,但它没有执行。我应该如何在其中写入我的 变量?
通常,当我单击按钮时,应触发更新 Firebase 中的赞成值的请求,但没有任何反应。
代码没有执行,但我没有收到任何错误。
代码:
文件.ejs
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.0/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "info",
authDomain: "info",
databaseURL: "info",
storageBucket: "info",
messagingSenderId: "info"
};
firebase.initializeApp(config);
</script>
<div class ="containerMarginsDetails">
<h1 class= "detailsTitle"><%=post.title %></h1>
<div class="row">
<img class = "postImg" src="/images/uploads/<%= post.image %>">
<span class="UpvoteButton"> </span><span class="DownvoteButton"> </span> <span class="HP"><%= post.upvotes - post.downvotes%> HP</span>
</div>
</div>
<script>
var upvotesRef = firebase.database().ref("posts/fun/<%=id%>/upvotes");
var downvotesRef = firebase.database().ref("posts/fun/<%=id%>/downvotes");
$('.UpvoteButton').click(function () {
upvotesRef.transaction(function (upvotes) {
if (!upvotes) {
upvotes = 0;
}
upvotes = upvotes - 1;
return upvotes;
});
});
</script>
这是路由器文件。
文件.js
var express = require("express");
var router = express.Router();
var firebase = require("firebase");
router.get('/details/:id', function(req, res){
global.page_name = "fun";
var id = req.params.id;
var funPostRef = firebase.database().ref("posts/fun/"+id);
funPostRef.once('value', function(snapshot){
var funPost = snapshot.val();
res.render('fun/details', {post: funPost, id:id});
});
});
module.exports = router;
注意:Firebase 也在我的 app.js 文件中进行了初始化。
编辑:
如果我尝试这个版本的代码,firebase 请求会在我每次重新加载页面时触发,而不是在我点击时触发。如何确保仅在单击时触发?
<% var upvotesRef = firebase.database().ref("posts/fun/"+id+"/upvotes");
var downvotesRef = firebase.database().ref("posts/fun/"+id+"/downvotes"); %>
$('.UpvoteButton').click(function () {
<% upvotesRef.transaction(function (upvotes) {
if (!upvotes) {
upvotes = 0;
}
upvotes = upvotes + 1;
return upvotes;
}); %>
});
编辑 2:
发现错误!什么意思?
这很奇怪,因为我在单击按钮时通过了身份验证,这些是我的安全规则:
{
"rules": {
".read": "true",
".write": "auth != null"
}
}
编辑 3:
我之前也收到以下(非崩溃)错误消息:
主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响。如需更多帮助,请查看https://xhr.spec.whatwg.org/。
编辑 4:
如果我将规则更改为:
{
"rules": {
".read": "true",
".write": "true"
}
}
按钮效果很好!
但是为什么我通过了身份验证,代码却不能使用前面的规则???
【问题讨论】:
标签: javascript jquery node.js firebase