乐闻世界logo
搜索文章和话题

How to send the data from .ejs file to .js file?

1个答案

1

In web development, sending data from .ejs files (which are Embedded JavaScript templates) to .js files (typically server-side JavaScript files or client-side JavaScript scripts) usually involves several steps. However, it is important to note that in most cases, data is passed from .js files to .ejs files, not the other way around. Here, we distinguish between two scenarios: one involving server-side usage with Node.js and Express, and the other involving client-side processing.

Server-side: Node.js + Express

In this scenario, .ejs files serve as template files for generating HTML, while .js files typically refer to server-side scripts, such as Express route handlers. In this case, data is typically passed from .js files to .ejs files, not the other way around. Here is a common example:

  1. Setting up Express and EJS First, you need to install and configure Express and EJS in your Node.js project.

    javascript
    const express = require('express'); const app = express(); // Set EJS as the view engine app.set('view engine', 'ejs'); // Set the views directory app.set('views', path.join(__dirname, '/views'));
  2. Route Handling In Express route files, you can pass data to the .ejs template for rendering.

    javascript
    app.get('/', (req, res) => { const data = { message: "Hello from server" }; res.render('index', data); });

    Here, the data object contains the data to be passed to the index.ejs template.

  3. Using Data in EJS Template In the index.ejs file, you can use <%= message %> to display data passed from the .js file.

    html
    <!DOCTYPE html> <html> <head> <title>My Page</title> </head> <body> <h1><%= message %></h1> </body> </html>

Client-side

If you want to send data from the HTML generated by client-side .ejs files to client-side .js files, the common approach is to embed data within the HTML and then read it in the .js file.

  1. Embedding Data in HTML In index.ejs, you can embed data into HTML elements' data attributes or define global variables within <script> tags.

    html
    <div data-message="<%= message %>"></div> <script> var messageFromServer = "<%= message %>"; </script>
  2. Reading Data in JavaScript In client-side .js files, you can retrieve this data by querying DOM elements' data attributes or using global variables.

    javascript
    // Using data attributes const message = document.querySelector('div').dataset.message; // Using global variables console.log(messageFromServer);

Summary: Typically, data is sent from .js files to .ejs files, especially in server-side rendering scenarios. For client-side processing, data is usually passed through HTML.

2024年7月20日 03:51 回复

你的答案