要实现将后端从 MySQL 获取的数据用前端显示出来,可以通过以下步骤操作:

  1. 在后端编写相应的接口,用于从 MySQL 数据库获取数据。可以使用后端语言(如 Python、Node.js 等)连接数据库并执行查询操作,将查询结果返回给前端。

  2. 在前端页面中使用 Ajax 或 Fetch 等方式向后端发送请求,调用后端接口获取数据。

  3. 在前端页面中编写 JavaScript 代码,将后端返回的数据进行处理和展示。可以使用 DOM 操作相关的 API 将数据渲染到页面上,例如使用 innerHTML 或 appendChild 等方法将数据插入到指定的 HTML 元素中。

以下是一个示例代码,以使用 JavaScript 和 Ajax 获取后端数据并展示在前端页面上为例:

后端(使用 Node.js 和 Express 框架示例):

const express = require('express');
const mysql = require('mysql');

const app = express();
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

app.get('/data', (req, res) => {
  connection.query('SELECT * FROM table_name', (error, results, fields) => {
    if (error) throw error;
    res.send(results);
  });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

前端:

<!DOCTYPE html>
<html>
<head>
  <title>Display Data</title>
</head>
<body>
  <div id='dataContainer'></div>

  <script>
    const dataContainer = document.getElementById('dataContainer');

    // 使用 Ajax 向后端发送请求
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/data', true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          const data = JSON.parse(xhr.responseText);
          // 处理后端返回的数据
          data.forEach(item => {
            const p = document.createElement('p');
            p.textContent = item.name;
            dataContainer.appendChild(p);
          });
        } else {
          console.error('Error:', xhr.status);
        }
      }
    };
    xhr.send();
  </script>
</body>
</html>

以上示例代码中,后端使用了 Node.js 和 Express 框架创建了一个简单的服务器,提供了一个/data的接口,用于从 MySQL 数据库中查询数据并返回给前端。前端使用了 JavaScript 和 Ajax 向后端发送 GET 请求,通过处理后端返回的数据,将数据展示在前端页面上的dataContainer元素中。

如何将后端从 MySQL 获取的数据显示在前端页面上

原文地址: https://www.cveoy.top/t/topic/qp3h 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录