How to Use Data of a JSON in JavaScript with Ajax

In JavaScript Technology

When using the data of JSON file in HTML document some errors that could occur. One of them that usually happens is as follows:

  • Access to XMLHttpRequest has been blocked by CORS policy

Here is an example of a test.

Step 1. Created JSON file New.json

[
    { "firstname":"Thomas", "lastname":"Anderson" },
    { "firstname":"Agent", "lastname":"Smith" },
    { "firstname":"Agent", "lastname":"Brown" }
]

Step 2. And to get the data from JSON file try the following code:

<script type="application/javascript">
            $(document).ready(function() {
                $("div").click(function () {
                    $.ajax({
                        type: 'GET',
                        url: './New.json',
                        dataType: 'json',
                        success: function(data){
                            window.alert(data);
                        },
                    });
                });
            });
    </script>

As a result got the following error: Access to XMLHttpRequest has been blocked by CORS policy

https://i.stack.imgur.com/iC20z.png
Access to XMLHttpRequest has been blocked by CORS policy error screenshot

One of the solutions could be instead of surrounding the list of elements with {} which produces an invalid object, use [] to make a valid array.

If that doesn’t help read the following guide Cross-domain Ajax with Cross-Origin Resource Sharing

Click here to view original web page at stackoverflow.com