You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中为Mustache.js模板的HTML Select实现事件监听与动态填充

我来帮你搞定这个两个Select动态联动的需求,结合你用的Node.js v8.9.4、Mustache.js技术栈,咱们分后端接口准备、前端模板渲染和动态交互三个部分来实现:

1. 后端:搭建接口与初始页面渲染

首先咱们用Express来搭建HTTP服务器(注意:Node.js v8.9.4兼容Express 4.x版本,别装太新的版本),需要做四件事:

  • 准备模拟的实验和患者数据(你可以替换成从数据库读取的逻辑)
  • 提供获取实验列表的接口
  • 提供根据实验ID获取对应患者数据的接口
  • 用Mustache渲染包含初始Select的HTML页面

下面是核心代码示例:

const express = require('express');
const mustacheExpress = require('mustache-express');
const app = express();

// 配置Mustache模板引擎
app.engine('mustache', mustacheExpress());
app.set('view engine', 'mustache');
app.set('views', __dirname + '/views');

// 模拟数据:你可以替换成数据库查询逻辑
const mockData = {
  experiments: [
    { id: 'exp1', name: '实验A' },
    { id: 'exp2', name: '实验B' },
    { id: 'exp3', name: '实验C' }
  ],
  patients: {
    exp1: [
      { id: 'p1', name: '患者甲' },
      { id: 'p2', name: '患者乙' }
    ],
    exp2: [
      { id: 'p3', name: '患者丙' },
      { id: 'p4', name: '患者丁' }
    ],
    exp3: [
      { id: 'p5', name: '患者戊' }
    ]
  }
};

// 渲染初始页面,用Mustache填充第一个Select的选项
app.get('/', (req, res) => {
  res.render('index', { experiments: mockData.experiments });
});

// 根据实验ID获取对应患者数据的接口
app.get('/api/patients', (req, res) => {
  const experimentId = req.query.experimentId;
  const patients = mockData.patients[experimentId] || [];
  res.json(patients);
});

app.listen(3000, () => {
  console.log('服务器运行在http://localhost:3000');
});
2. 前端:Mustache模板与动态联动逻辑

在你的views目录下创建index.mustache模板文件,用Mustache循环渲染第一个Select的选项,然后编写JavaScript监听第一个Select的变化,动态请求患者数据并填充第二个Select:

<!DOCTYPE html>
<html>
<head>
  <title>实验-患者联动选择</title>
</head>
<body>
  <h3>选择实验:</h3>
  <select id="experimentSelect">
    <!-- Mustache循环填充实验选项 -->
    {{#experiments}}
    <option value="{{id}}">{{name}}</option>
    {{/experiments}}
  </select>

  <h3>选择患者:</h3>
  <select id="patientSelect">
    <!-- 初始为空,等待动态填充 -->
    <option value="">请先选择实验</option>
  </select>

  <script>
    // 获取两个Select元素
    const experimentSelect = document.getElementById('experimentSelect');
    const patientSelect = document.getElementById('patientSelect');

    // 监听实验Select的变化事件
    experimentSelect.addEventListener('change', function() {
      const selectedExperimentId = experimentSelect.value;
      if (!selectedExperimentId) {
        // 如果没有选择,重置患者Select
        patientSelect.innerHTML = '<option value="">请先选择实验</option>';
        return;
      }

      // 用XHR发送请求(兼容Node.js v8.9.4对应的浏览器环境)
      const xhr = new XMLHttpRequest();
      xhr.open('GET', `/api/patients?experimentId=${selectedExperimentId}`, true);
      xhr.onload = function() {
        if (xhr.status === 200) {
          const patients = JSON.parse(xhr.responseText);
          // 清空患者Select并填充新选项
          patientSelect.innerHTML = '';
          patients.forEach(function(patient) {
            const option = document.createElement('option');
            option.value = patient.id;
            option.textContent = patient.name;
            patientSelect.appendChild(option);
          });
          // 如果没有患者数据,添加提示选项
          if (patients.length === 0) {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '该实验暂无患者数据';
            patientSelect.appendChild(option);
          }
        } else {
          patientSelect.innerHTML = '<option value="">加载患者数据失败</option>';
        }
      };
      xhr.onerror = function() {
        patientSelect.innerHTML = '<option value="">加载患者数据失败</option>';
      };
      xhr.send();
    });
  </script>
</body>
</html>
3. 关键注意事项
  • 依赖安装:需要安装兼容Node.js v8.9.4的包版本,执行命令:npm install express@4.18.2 mustache-express@1.3.2
  • 数据替换:示例中的mockData只是模拟数据,你可以把这部分逻辑替换成从数据库(如MySQL、MongoDB)查询的代码,实现真实数据的联动
  • 兼容性:用XHR而不是fetch是因为部分旧浏览器对fetch的支持有限,如果你不需要兼容老环境,也可以换成fetch写法

内容的提问来源于stack exchange,提问作者Marco Ribolla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:15:19