简体   繁体   中英

How to send and use data in ejs or jade with node js server?

I am sending localstorage data from ajax to node js server with ajax, so that to use that data to decorate html page with ejs or jade. I tried to send my data to ejs or jade by rendering it after getting with app.post. It compiles, but I can not find movies variable in ejs file.

app.post('/notes' , function (req , res) {
   var name = req.body;
   res.render('/bucket',{movies:name});
});

In client side I wrote like this, it can not find movies variable here:

function postData() {
        var clicked;
        if (localStorage.getItem("liked") === null)
            clicked = [];
        else
            clicked = localStorage.getItem("liked");

        $.ajax({
            type: 'POST',
            url: 'http://localhost:3000/notes',
            contentType: 'application/json',
            dataType: 'json',
            data : clicked,
            success: function (msg) {

            }
        });
    }
postData();
alert ("<%=movies%>");

Is there a way to do it?

instead of putting alert("<%=movies%>"); after postData(); - try putting alert(msg.movies); in the success handler that is now empty and which is the only place (in your example) where you can use the AJAX response.

In your bucket.jade template, try including the below lines after your postData() function.

  script.
    alert("#{movies}")

I tried a example here, and it worked perfectly.

Hope this helps!

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