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

JavaScript导入JSON数据库报错求助:模块语法与函数未定义问题

解决JavaScript模块导入与函数未定义问题

问题背景

自学JavaScript不久,尝试从JSON数据库读取数据并通过按钮调用函数展示,但遇到两个报错:

  • Uncaught SyntaxError: Cannot use import statement outside a module
  • Uncaught ReferenceError: showData is not defined at HTMLButtonElement.onclick

当前代码如下:

index.html

<head>
  <script src="script.js" type="text/javascript"></script>
  <script src="db_connection.js" type="module"></script>
</head>
<body>
  <button onclick="showData()">Show Data</button>
</body>

script.js

import { data } from "./db_connection.js";
function showData() {
  console.log(data[0].name);
}

db_connection.js

import data from "./database.json" assert { type: "json" };
export default { data };

database.json

[
  { "id": 1, "name": "Jason", "year": 2020 },
  { "id": 2, "name": "Freddy", "year": 2021 }
]

解决方案

1. 统一设置JS文件为模块类型

浏览器仅在脚本声明为type="module"时支持import/export语法,需将script.js也标记为模块,同时建议将脚本放在body末尾,确保DOM元素加载完成:

<!-- 修改后的index.html -->
<body>
  <button id="showBtn">Show Data</button>
  <script src="db_connection.js" type="module"></script>
  <script src="script.js" type="module"></script>
</body>

2. 修正模块导入导出匹配

db_connection.js当前导出的是包含data属性的对象,和script.js的解构导入不匹配,修改为直接导出数据:

// 修改后的db_connection.js
import data from "./database.json" assert { type: "json" };
export default data; // 直接导出JSON数组

对应调整script.js的导入方式:

// 修改后的script.js
import data from "./db_connection.js";

function showData() {
  console.log(data[0].name);
}

3. 解决模块函数无法全局访问的问题

模块内部函数默认隔离在私有作用域,onclick="showData()"无法直接调用,推荐使用事件监听绑定按钮事件:

// 修改后的script.js
import data from "./db_connection.js";

function showData() {
  console.log(data[0].name);
}

// 页面加载完成后绑定点击事件
document.addEventListener('DOMContentLoaded', () => {
  const btn = document.getElementById('showBtn');
  btn.addEventListener('click', showData);
});

若仅需快速验证功能,也可临时将函数挂载到全局作用域(不推荐用于大型项目):

// 临时测试用
window.showData = showData;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 19:43:28