简体   繁体   English

从ejs文件导出变量

[英]exporting variable from ejs file

I print files from an array (that is stored in my app.js file) to a website using a for-loop in ejs: 我使用ejs中的for循环将文件(存储在app.js文件中)从数组打印到网站:

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

Now I want to be able to remove a specific object from my array, I would use 现在,我希望能够从数组中删除特定对象,我将使用

array.splice(i,1)

The problem is that I don't know how to export the “i” variable of a specific looped item from my ejs file to my app.js 问题是我不知道如何将特定循环项目的“ i”变量从我的ejs文件导出到我的app.js中

(using node and express) (使用节点和快递)

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

Constant data like this stored in memory. 这样的常量数据存储在内存中。 store in front-end memory instead. 而是存储在前端内存中。

Otherwise, you need to implement an api route, and send a http request and refresh or change dom in browser to deal with this question. 否则,您需要实现api路由,并发送http请求并在浏览器中刷新或更改dom来处理此问题。

I am assuming that on the trigger of an event you want to delete one of the posts. 我假设在事件触发时您想要删除其中一个帖子。 You can do that using the post method provided by jQuery. 您可以使用jQuery提供的post方法来做到这一点。 The JavaScript file would be as follows: 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
        });
    });

The above code sends a POST request to '/route_name' on the trigger of 'event_name', and after the completion of the request you can return some data which is passed as argument to the callback function. 上面的代码在'event_name'的触发器上将POST请求发送到'/ route_name',在请求完成后,您可以返回一些数据,该数据作为参数传递给回调函数。 The app.js file should have the following middleware: 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);
});

Make sure to include the body-parser module, otherwise you would not be able to access the data in a req.body object and you will probably get an error. 确保包括body-parser模块,否则您将无法访问req.body对象中的数据,并且可能会收到错误消息。

You can also use the http request object to perform the ajax request but i usually prefer to use jQuery. 您也可以使用http请求对象执行ajax请求,但我通常更喜欢使用jQuery。

Okay so in case anyone else has the same problem, I used a hidden input field in a form that looks like this: 好的,以防万一其他人遇到相同的问题,我使用了如下形式的隐藏输入字段:

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

i is the variable and you can access it in the app.js via req.body.prodId 我是变量,您可以通过req.body.prodId在app.js中访问它

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

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