How do I import variables from NodeJS to JS?

时间:2015-11-12 11:14:38

标签: javascript node.js client-side server-side

How can I use static variables in an JS file?

I'm using nodeJS with ejs templates. In HTML it works if i use <%= colors %> but i want to use the content of color in clientside js.

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.

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

in the index.ejs template, i can call "blue" via:

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

. now i have a separate client-side functions.js file. i want to access "blue" in this file.

2 个答案:

答案 0 :(得分:5)

Your first problem is that var color[] = is not valid JavaScript.

You seem to be getting it mixed up with 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.

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. You probably want a string literal there, so you need to encode your text as JavaScript literals.

That is more or less the same as JSON so:

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:

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

答案 1 :(得分:0)

好的,我找到了解决方法。

我现在在我的index.ejs模板中有这个:

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

我在下一行调用我的functions.js(客户端)。 现在我可以使用:

{{1}}

。 如果有更好的解决方案(jquery代码不是我用过的),请发表评论!