0

I stumbled an issue where I'm working on an HTML file that would load a separate json file. The HTML file have JS code in the <script></script> tag and the json file contains an array with some objects. Both HTML and JSON are stored on my hard drive and my HTML will load using a file path to direct to a file on my PC, not a URL across the internet, to the json file, akin to img src tag using a relative path to an image on my PC.

This video: https://www.youtube.com/watch?v=nx8E5BF0XuE told me that due to the CORS policy made the $.ajax to grab the file stored on his PC, a server is required.

I originally tried doing this before being aware of that video:

        (async () => { 
            const List = await (await fetch("FileWithObjects.json")).json() 
        })() 

And got a similar error: enter image description here

If I do not want to use a server as well as node.js, do I HAVE TO have the JSON data in the HTML file itself?

AAsomb113
  • 61
  • 5
  • This answer says you can just link to it https://stackoverflow.com/a/45424256/1690193 You definitely can't use any ajax, get ,fetch methods to get a static file. i imagine you need to link to a javascript file that sets a javascript variable to the JSON then you can use that later. In fact I might try it myself now – Nick.Mc Apr 30 '23 at 02:05

1 Answers1

0

I couldn't find a useful answer online that I could believe so I tried it myself

Instead of a JSON file you need a javascript file that sets a javascript variable to the JSON.

index.htm

The HTML file references a local javascript file via <script src

<!DOCTYPE html>
<html>
  <head>
    <script src="script1.js"></script>
  </head>
  <body>
    <div id="mydiv"></div>
  <script>
    console.log(j);
    setTimeout(() => 
        {
            document.getElementById("mydiv").innerHTML=j.stuff[2];
        } , 
        5000  
    )
  </script>

  </body>
</html>

script1.js

This is in the same folder as index.htm

Note this is a javascript file that sets javascript variable j to the JSON you want.

j=
{
    "stuff": [0,1,2,3,4,5,6]
}

If you open the web page, you'll see a tiny 2 in the top left corner from the static json file

Note that you can only manipulate JSON (or do any non-presentation "computational" things) via javascript. You can't do anything with JSON with HTML alone.

All methods such as get, fetch, ajax can only load data from a "web service", which in turn requires a web server

Nick.Mc
  • 18,304
  • 6
  • 61
  • 91