问题:
我的脚本标记中有一些 Firebase 代码,但它没有执行。我应该如何在其中写入我的 <%=id%> 变量?
通常情况下,当我点击按钮时,应该会触发一个请求来更新 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"
}
}
按钮工作完美!
但是,尽管我已通过身份验证,但为什么代码不符合之前的规则???
最佳答案
由于您使用的是模板语言,因此不需要 +
运算符:
var upvotesRef = firebase.database().ref("posts/fun/<%=id%>/upvotes");
关于javascript - 如何将 Node.js 变量放入我的 <script></script> 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40408945/