简体   繁体   English

如何使用Node JS服务器在EJS或Jade中发送和使用数据?

[英]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. 我将使用ajax将本地存储数据从ajax发送到节点js服务器,以便使用该数据用ejs或jade装饰html页面。 I tried to send my data to ejs or jade by rendering it after getting with app.post. 在尝试获取app.post之后,我尝试通过渲染将数据发送到ejs或jade。 It compiles, but I can not find movies variable in ejs file. 它可以编译,但是在ejs文件中找不到电影变量。

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%>"); 而不是发出alert("<%=movies%>"); after postData(); postData(); - try putting alert(msg.movies); -尝试放置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. 在成功处理程序中,现在为空,这是(在您的示例中)唯一可以使用AJAX响应的地方。

In your bucket.jade template, try including the below lines after your postData() function. 在您的bucket.jade模板中,尝试在postData()函数之后postData()以下postData()行。

  script.
    alert("#{movies}")

I tried a example here, and it worked perfectly. 我在这里尝试了一个示例,并且效果很好。

Hope this helps! 希望这可以帮助!

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

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