简体   繁体   English

如何将变量从NodeJS导入JS?

[英]How do I import variables from NodeJS to JS?

How can I use static variables in an JS file? 如何在JS文件中使用静态变量?

I'm using nodeJS with ejs templates. 我正在使用带有ejs模板的nodeJS。 In HTML it works if i use <%= colors %> but i want to use the content of color in clientside js. 在HTML中,如果我使用<%= colors %>但我想在客户端js中使用color的内容,则可以使用。

i think it should look like: 我认为它应该看起来像:

var color[] = <%= colors =>

would be nice to know what im doing wrong. 知道我在做什么错会很高兴。 Thank you! 谢谢!

Marius 马吕斯

edit: to clear things up, i've written the question fast so it seems i've forgotten to explain some things. 编辑:为了解决问题,我已经快速写了这个问题,所以似乎我忘记了解释一些事情。

colors is an array send by the nodeJS express server. colors是由nodeJS express服务器发送的数组。

var colors = ['blue', 'red', 'green'];

in the index.ejs template, i can call "blue" via: 在index.ejs模板中,我可以通过以下方式调用“蓝色”:

<span>    
  <%= colors[0] %>
</span>

. now i have a separate client-side functions.js file. 现在我有一个单独的客户端functions.js文件。 i want to access "blue" in this file. 我想访问此文件中的“蓝色”。

Your first problem is that var color[] = is not valid JavaScript. 您的第一个问题是var color[] =无效的JavaScript。

You seem to be getting it mixed up with PHP. 您似乎将其与PHP混合使用。 The syntax you are looking for is probably: 您正在寻找的语法可能是:

var color = [];
color.push(someValue);

We can't tell what your server side code is going to output for <%= colors => but I'll bet it is something like blue . 我们无法确定<%= colors =>的服务器端代码将输出什么,但我敢打赌,它类似于blue

var color = [];
color.push(<?= colors =>);

would therefore give you: 因此会给你:

var color = [];
color.push(blue);

… which is fine, so long as you have a variable called blue already. …很好,只要您已经有一个名为blue的变量即可。 You probably want a string literal there, so you need to encode your text as JavaScript literals. 您可能在那里需要一个字符串文字,因此您需要将文本编码为JavaScript文字。

That is more or less the same as JSON so: 这与JSON大致相同,因此:

var color = [];
color.push(<?= JSON.stringify(colors) =>);

… will probably do the job. ……可能会胜任。

If colors isn't blue but is actually an array, then you would probably want to just dump the whole thing to the variable in one go: 如果colors不是blue而是实际上是一个数组,那么您可能只想一次性将整个内容转储到变量中:

var color = <?= JSON.stringify(colors) =>;

Okay, i found a workaround. 好的,我找到了解决方法。

i have now this in my index.ejs template: 我现在在我的index.ejs模板中有这个:

<script>
  var colors = [<%= colors %>];
</script>

and i call my functions.js (client-side) in the next line. 然后在下一行中调用我的functions.js(客户端)。 now i can use: 现在我可以使用:

$("span").text(colors[0]);

. if there's a better solution (the jquery code isnt exactly what i've used), please comment! 如果有更好的解决方案(jQuery代码与我使用的代码不完全相同),请发表评论!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM