简体   繁体   中英

How can I send data to my frontend js files in express

I am using ejs to render my html pages and am passing in data like this:

        collection.find({}).toArray(
            function (err, results) {
                res.render('index', {
                    results: results,
                    nav: nav
                });
            });

This works great, however I would like to send some data to my frontend js files to keep from using inline javascript in my rendered HTML. is there a standard way to implement this? I have tried renaming my js files with an ejs extension and rendering them as well, however this did not work.

You can use Ajax, just create and endpoint what is send back JSON. For example:

Server - getData

collection.find({}).toArray(
  function (err, results) {
    res.json({data:results});
});

Clinet - jQuery

$.getJSON( "server-url/getData", function( result ) {
  // Do whatever what you want with this data
  console.log(result.data)
});

More details: $.getJSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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