简体   繁体   English

Nodejs,Express如何在外部JavaScript文件中传递变量以进行路由和使用?

[英]Nodejs, Express How to pass variable to route and use it in external JavaScript file?

I am working on a web app using MongoDB Express NodeJS stack and in one of the routes I am getting array from database and then passing it to route. 我正在使用MongoDB Express NodeJS堆栈的Web应用程序上工作,并且在其中一种路由中,我从数据库中获取数组,然后将其传递给路由。 Code: 码:

app.get("/badges/new", function(req, res) {
    Colour.find({}, function(err, foundCoulours) {
        if(err){
            console.log("error: "+ err);
            res.redirect("back");
        } else {
            res.render("badges/new",{foundCoulours:foundCoulours})
        }
    });
});

All done easily but here is a bit that I am stuck at the moment: I want to use jQuery to add elements onto the page depending on the result that came from server. 一切都很容易完成,但此刻我有些卡住:我想使用jQuery根据服务器的结果将元素添加到页面上。 I can do it using script tag and in-line JS on the ejs file without any problems but what I would like to do is to use external JavaScript file so my ejs wouldn't look as massive just with <script src="public/foo.js"></script> . 我可以在ejs文件上使用脚本标记和内联JS来完成此操作,而不会出现任何问题,但是我想做的是使用外部JavaScript文件,这样我的ejs就不会像使用<script src="public/foo.js"></script> Question: Is there a way to pass foundCoulours to "public/foo.js" file after it was passed to route? 问题:有没有办法在将路由传递到路由之后将foundCoulours传递到"public/foo.js"文件? Or maybe I can pass it straight to "public/foo.js" file from the request route. 或者,也许我可以将其直接从请求路由传递到"public/foo.js"文件。

You can sequentially load the scripts. 您可以顺序加载脚本。 As below: 如下:

Jade

body
script(type='text/javascript').
      var foundCoulours= #{foundCoulours}
script(type='text/javascript', src="foo.js")

EJS EJS

<script>
 var foundCoulours = <%= foundCoulours>
</script>
<script src="public/foo.js"></script>

Explained: As we are loading foundCoulours variable in global scope, it is directly accessible in foo.js, as it is loaded after the variable is initialized. 解释:在全局范围内加载foundCoulours变量时,可以在foo.js中直接访问它,因为它是在变量初始化之后加载的。

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

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