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

无法基于EJS外部变量过滤数据:用户兴趣国筛选高校库失败

问题原因及解决方法

核心原因

  • 执行环境完全分离:你写在<script>标签里的代码是在浏览器客户端运行的,而EJS模板里的<% %>代码是在服务器端运行的。服务器渲染页面时,根本访问不到浏览器的sessionStorage和你定义的country变量,自然会提示“country is not defined”。
  • 变量作用域隔离:客户端的country变量只存在浏览器的JS运行环境中,服务器端的EJS模板在生成HTML时,这个变量还不存在于服务器的上下文里。

解决方法

方法1:服务器端获取变量后传给EJS模板

把用户的interestedcountry数据传到服务器端(比如通过URL参数、用户会话、接口请求等),服务器拿到后将变量注入EJS模板:

  1. 服务器端代码(以Express为例):
app.get('/university-list', (req, res) => {
  // 这里假设从用户会话或请求参数中获取country
  const country = req.session.userInfo?.interestedcountry || req.query.country;
  // 把country和universities一起传给EJS模板
  res.render('university-template', { universities, country });
});
  1. EJS模板中直接使用变量:
<% const suggestedUniversities = universities.filter(row => row.location.includes(country)) %>
<!-- 后续渲染逻辑不变 -->

方法2:客户端动态渲染列表

如果不想修改服务器端逻辑,可以让服务器把所有高校数据传给客户端,然后在浏览器端用JS筛选并生成DOM:

<!-- 服务器先将高校数据转为JSON注入客户端 -->
<script>
  // 从服务器获取全量高校数据
  const allUniversities = <%= JSON.stringify(universities) %>;
  
  // 获取用户感兴趣的国家
  const UserInfo = JSON.parse(sessionStorage.getItem("user-info"));
  const country = UserInfo.interestedcountry;

  // 筛选高校并动态渲染
  const suggestedUniversities = allUniversities.filter(row => row.location.includes(country));
  const scrollContainer = document.querySelector('.horizontalMobileScroll');
  
  suggestedUniversities.forEach(row => {
    const cell = document.createElement('div');
    cell.className = 'horizontalMobileScroll__cell';
    cell.innerHTML = `
      <div class="horizontalScroll">
        <a href="/university/${row.id}">
          <img src="../../../statics/aalto-uni-logo.png" style="margin: 10px; width: 50px; height: auto;">
          <h2 class="uniName">${row.name}</h2>
          <h2 class="uniPlace">${row.location}</h2>
        </a>
      </div>
    `;
    scrollContainer.appendChild(cell);
  });
</script>

内容的提问来源于stack exchange,提问作者Jasmine Nurul Izza Bachtiar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:30:57