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

为何select标签无法将值传递至Express的req.query?

解决Express + Handlebars排序功能无响应及req.query.sort为空的问题

一、前端表单提交失败的原因及修复

你的onchange="sort-form.submit()"写法错误:HTML元素ID中的减号-不能直接作为JavaScript标识符使用,浏览器会把sort-form解析成sort - form,导致找不到表单对象。

同时Handlebars模板中,带减号的对象属性不能用.语法访问,必须改用[]语法,否则会被解析成表达式计算,导致选中状态判断失效。

修正后的前端代码:

<div class="input-group">
  <form action="/" method="GET" id="sort-form">
    <select class="form-select text-center" name="sort" id="sort" onchange="this.form.submit()">
      <option value="a-z"{{#if sort['a-z']}} selected{{/if}}>A->Z</option>
      <option value="z-a"{{#if sort['z-a']}} selected{{/if}}>Z->A</option>
      <option value="category" {{#if sort.category}} selected{{/if}}>類別</option>
      <option value="location" {{#if sort.location}} selected{{/if}}>地址</option>
    </select>
  </form>
</div>

二、后端Express排序逻辑的问题修复

当没有传入sort参数时,sortValue为undefined,此时sortOption[sortValue]会返回undefined,传给MongoDB的sort()方法会报错。需要给sortValue设置默认值,确保排序逻辑始终有效。

修正后的app.js代码:

app.get("/", (req, res) => {
  const sortValue = req.query.sort || "a-z"; // 设置默认排序规则
  console.log(sortValue);
 
  const sortOption = {
    "a-z": { name: "asc" },
    "z-a": { name: "desc" },
    category: { category: "asc" },
    location: { location: "asc" },
  };

  // 构建用于模板回显选中状态的sort对象
  const sort = {};
  sort[sortValue] = true;

  Restaurant.find()
    .lean()
    .sort(sortOption[sortValue])
    .then((restaurantList) => res.render("index", { restaurantList, sort }))
    .catch((error) => console.error(error));
});

三、JavaScript获取select标签值的方法

有两种常用方式:

  • 直接获取select元素的value属性(推荐):
const selectElement = document.getElementById('sort');
const selectedValue = selectElement.value;
  • 通过选中的option元素获取(可同时获取选项文本):
const selectElement = document.getElementById('sort');
const selectedOption = selectElement.options[selectElement.selectedIndex];
const selectedValue = selectedOption.value;
const selectedText = selectedOption.textContent; // 获取选项显示的文字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:45:37