I just barely started learning JavaScript by myself and have a question to ask.
I have a JSON database I created, and a JavaScript file connecting to this same db, on another js file I have a function that I call with a button, how can I get the data from my JSON database into the js file with the function?
Here’s how my code looks like right now
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 } ]
The console returns "Uncaught SyntaxError: Cannot use import statement outside a module" and "Uncaught ReferenceError: showData is not defined at HTMLButtonElement.onclick"
Can anyone help?
>Solution :
I add code below.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript JSON Example</title>
<script src="script.js" type="module"></script>
<script src="db_connection.js" type="module"></script>
</head>
<body>
<button onclick="showData()">Show Data</button>
</body>
</html>
script.js:
// script.js
import { data } from "./db_connection.js";
export function showData() {
console.log(data[0].name);
}
db_connection.js:
javascript
Copy code
// db_connection.js
import data from "./database.json";
export { data };
database.json:
[
{ "id": 1, "name": "Jason", "year": 2020 },
{ "id": 2, "name": "Freddy", "year": 2021 }
]