繁体   English   中英

从ejs文件导出变量

[英]exporting variable from ejs file

我使用ejs中的for循环将文件(存储在app.js文件中)从数组打印到网站:

<% for(let i = 0;i<posts.length; i++){ %>
    <li class="listtitle">
         <%= posts[i].title %>
      </li>
  <% } %>

现在,我希望能够从数组中删除特定对象,我将使用

array.splice(i,1)

问题是我不知道如何将特定循环项目的“ i”变量从我的ejs文件导出到我的app.js中

(使用节点和快递)

我认为您可以使用javascript使用请求将数据发送到后端

这样的常量数据存储在内存中。 而是存储在前端内存中。

否则,您需要实现api路由,并发送http请求并在浏览器中刷新或更改dom来处理此问题。

我假设在事件触发时您想要删除其中一个帖子。 您可以使用jQuery提供的post方法来做到这一点。 JavaScript文件如下所示:

let posts = document.querySelectorAll(".listtitle");
for(let i = 0; i < posts.length; i++) {
    posts[i].addEventListener('event_name', function(){
        $.post('/route_name', {index: i}, function(data){
            //perform whatever changes you want to do in the front end
        });
    });

上面的代码在'event_name'的触发器上将POST请求发送到'/ route_name',在请求完成后,您可以返回一些数据,该数据作为参数传递给回调函数。 app.js文件应具有以下中间件:

app.post('route_name', function(req, res){
    //req.body would contain the data sent through the request, in this case req.body.index
    //access and make changes to the database
    //After making changes you can return some data which will be passed to the callback 
    res.send(posts);
});

确保包括body-parser模块,否则您将无法访问req.body对象中的数据,并且可能会收到错误消息。

您也可以使用http请求对象执行ajax请求,但我通常更喜欢使用jQuery。

好的,以防万一其他人遇到相同的问题,我使用了如下形式的隐藏输入字段:

  <input id="prodId" name="prodId" type="hidden" value=<%= i %>>

我是变量,您可以通过req.body.prodId在app.js中访问它

暂无
暂无

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

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