Home > database >  How can I display json data on the html using script.js?
How can I display json data on the html using script.js?

Time:02-01

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
</head>
<body>
    <div id="demo"></div>
    <script type="module" src="./js/script.js"></script>
</body>
</html>

script.js:

    import demo from './data.json'
    document.getElementById("demo").innerHTML = demo;
    console.log(demo)  

Error in the console:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.

JSON data locates near script.js in the same directory

How can I display JSON data on the HTML using script.js?

CodePudding user response:

Use JQuery.

<button onclick="showList()">Show List</button>

<script>
  function showList(){
    fetch("./data.json")
      .then(response => response.json())
      .then(data => createList(data));
  }
  
  function createList(data) {
    //code to process here
  }
</script>

My Source: https://www.tutorialstonight.com/display-json-data-in-html-page

CodePudding user response:

You can display JSON data on the HTML using something like this, accessing the data from the imported ./data.json file (If the JSON data is located in the same JavaScript file, you can simply assign the data to a variable and access it from there.) and rendering it, your code is correct but need JSON.stringify(demo) the data.

https://codesandbox.io/s/javascript-forked-s8w6d8?file=/index.html

For example, you can use the document.getElementById() method to select your with id="demo" and then set its innerHTML property to the JSON data.

 const demo = {
"name": "John",
"age": 30,
"city": "New York"
};

const demoDiv = document.getElementById("demo");

demoDiv.innerHTML = JSON.stringify(demo);

This will convert the JSON data to a string and display it

cheers

  • Related