简体   繁体   English

在前端 javascript 上处理从后端发送的数据

[英]Handle data sent from back-end on front-end javascript

I've got a NodeJS Express back-end.我有一个 NodeJS Express 后端。

When it receives a GET request to the route /messages/ , it fetches the messages in the database, builds an array called messageList and populate the view, which is then rendered to the user with no problem.当它接收到路由/messages/的 GET 请求时,它会在数据库中获取消息,构建一个名为messageList的数组并填充视图,然后毫无问题地呈现给用户。

Here's the code that handles the resquest, in the Express router messages.js :这是处理请求的代码,在 Express 路由器messages.js中:

router.get('/', async (req, res) => {
    const messageList = await req.app.get('messageHandler').get();
    res.render('messages', { messageList: messageList });
});

And here is part the view template in the messages.ejs file:这是messages.ejs文件中的视图模板的一部分:

<table>
    <% for (var i = 0; i < messageList.length; i++) { %>
        <tr id="msg-<%= i %>"><td><%= messageList[i].title %></td></tr>
    <% } %>
<table>

It all works perfectly fine and smooth.这一切都非常顺利。

However, I'd like to eventually handle these messages in the front-end side javascript, to apply a filter by suppressing the <tr> with a given id property.但是,我想最终在前端 javascript 中处理这些消息,以通过抑制具有给定id属性的<tr>来应用过滤器。

Is there a way to pass the array messageList to the front-end javascript, or to load it as a javascript array when the page is loaded??有没有办法将数组messageList传递给前端javascript,或者在页面加载时将其作为javascript数组加载?

Thanks in advance!提前致谢! =) =)

@Vinas from one of your comment @Vinas 来自您的一条评论

@OrAssayag Yes, but on the back-end part. @OrAssayag 是的,但在后端部分。 I want to have a copy of it on the front end, so I can handle i我想在前端有一个副本,这样我就可以处理我了

and

@GabrielLupu Let's say I implement a search field where the user can input the value he/she's looking for... I want to do it in the front-end, without having to make a new http request for it to be applied @GabrielLupu 假设我实现了一个搜索字段,用户可以在其中输入他/她正在寻找的值...我想在前端执行它,而无需提出新的 http 请求来应用它

You want the application response to handle res.render() & res.json()您希望应用程序响应处理res.render() & res.json()

which would throw an error so why not write another get route这会抛出一个错误,所以为什么不写另一个get route

like this像这样

router.get('/', async (req, res) => {
    const messageList = await req.app.get('messageHandler').get();
    res.render('messages', { messageList: messageList });
});

router.get('/api', async (req, res) => {
    const messageList = await req.app.get('messageHandler').get();
    res.json( messageList );
});

then its look something like this on the client然后它在客户端看起来像这样

<table>
    <% for (var i = 0; i < messageList.length; i++) { %>
        <tr id="msg-<%= i %>"><td><%= messageList[i].title %></td></tr>
    <% } %>
<table>

<script>
fetch('/api')
  .then(response => response.json())
  .then(data => console.log(data));
</script>

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

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