问题
I have a variable that i want to pass from NodeJs to EJS file . I need this variable to choose whether or not I display an alert().
while running my code i have "nbrow not defined"
server.js
con.query("SELECT * FROM entreprises WHERE identifiant =?",user, function (err, result) {
if (err) throw err;
console.log(result);
nbrow = result.length;
if(nbrow > 0)
{
res.send("Connexion info :" + user + " " + password);
}
else
{
res.render("connexion",{ nbrow: nbrow});
}
});
connexion.ejs
<script>
if(<%= nbrow %> = 0){
alert("user not exist");
}
</script>
I already searched on internet what could be wrong with my code but i found nothing that could help me.
my "if" is working fine same for my query and i'm connected to my database .
RE EDIT : someone asked me the view engine configuration, i don't really know what's that but i guess this is :
app.set('views', './views');
app.set('view engine', 'ejs');
回答1:
You are using single =
instead of ==
It should be:
<script>
if(<%= nbrow %> == 0){
alert("user not exist");
}
</script>
Also - regardless to this specific error.
EJS is rendered to html file, so in your browser you can always use 'view source' and see the actual rendered HTML. This way you can debug if the problem is in printing nbrow
or the script.
回答2:
My guess would be that the problem comes from this line :
nbrow = result.length;
This assumes that nbrow has already been defined elsewhere, but that's not the case, hence the "nbrow is not defined"
error
Try to put const
or let
in front of it :
const nbrow = result.length;
回答3:
<script>
var nbrow = JSON.parse('<%- JSON.stringify(nbrow) %>');
if(nbrow == 0)
alert("user not exist");
</script>
I do by stringify the variable and parse it back
来源:https://stackoverflow.com/questions/46646496/passing-variable-from-nodejs-to-ejs-file