1

The instructions then my code I have thus far is blow. I keep getting this error in the console on firefox web browser here: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/erice/Documents/project4/project4.json. (Reason: CORS request not http): Any help would be greatly appreciated, thank you!

Create an HTML file that reads a JSON file that contains the text based representation of the following object and displays the information stored in that JSON object.

    <html>
    <head>
        <!-- The <meta content> was used to stop an error with web browser -->
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
        <meta content="utf-8" http-equiv="encoding">
        <title>JSON to HTML</title>
        
<!--  jQuery library is a single JavaScript file -->
        <script src="https://code.jquery.com/jquery-3.3.1.js"
        integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
        crossorigin="anonymous"></script>

    </head>
    <body>

<!-- These are the div tags to display data from the JSON object -->

        <div> </div>

    <script>

        //Using jquery document.ready() to make a function available after the document is loaded()
        $(document).ready(function () {

        //reading json file using jquery getJSON() method
        $.getJSON("project4.json", function (data) {

        //This is using the html() method while displaying data like firstName/lastName.
        $("div").html("<p> <b> First Name : </b> " + data.firstName + "</p>");
        
        //html() completely replaces the element's content, whereas append() adds the new content at the end of any existing content.
        $("div").append("<p> <b> Last Name : </b> " + data.lastName + "</p>");
        $("div").append("<p> <b> grades : </b> " + data.grades + "</p>");
        $("div").append("<p> <b> credits : </b> " + data.credits + "</p>");
        });

    });
    </script>
    </body>

</html>

    {

    "firstName": "Eric",
    "lastName": "Clifford",

    "grades": 
    [
    
        "A",
        "B",
        "B",
        "A",
        "A",
        "B",
        "A",
        "A"
    
    ],
    "credits": 24

}
  • 1
    That is because your webpage is on some other domain(like localhost:3000/index.html) and you are accessing some other endpoint(like your JSON file). To prevent access of resources by some other person CORS introduced, please find here more about CROS https://stackoverflow.com/questions/25310450/cross-origin-resource-sharing-cors-concept Also you can move your JSON file in the same directory as that of your webpage to avoid this issue – Not A Bot Jun 26 '20 at 04:09

1 Answers1

0

you can use fetch(), which doesn't throw cross-origin errors. The documentation is here, but to summerize it, you would use
var info = fetch('target.url/here');
document.getElementById('target_element').innerHTML = info;

Ian Swift
  • 69
  • 1
  • 10