How would I go about getting a json file into javascipt?

116
March 07, 2022, at 2:10 PM

I'm extremely new to javascript, so assume I know nothing. I'm trying to import this json file into my website, and having issues getting it working. Currently, I'm trying out jquery's $.getJSON() method, but it returns with this error code:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/edgib102/Documents/GitHub/First-Website/data.json. (Reason: CORS request not http).

I tried looking online about it but nothing useful came up, so here I am. Any help at all would be much appreciated, I've been stuck on this for 2 days now and it's brought my progress to a standstill.

Github

Answer 1
  1. You cannot import a JSON file in a script tag

  2. You cannot AJAX a JSON file from file system - if you can upload the files to the same webserver (could be a locally run server), then you CAN AJAX it - NOTE the server needs to send correct CORS headers if the server has a different ORIGIN (for example port number)

  3. Alternatively change the JSON file to a JS file:

    const data = { "object-data": { 
        your data 
      }
    };
    

and then import it using

<script src="data.js"></script>
Answer 2

This issue is because of safety. Because of a security reason you cannot import a Json file in to your code because it contains data that could have some effects on the websites.

Your error caused by :

<script type="text/javascript" src="data.json"></script>

You can use Jquery and ajax to import it.

Step1: use jquery CDN

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>

Step2:

$.getJSON('dataenter code here.json', function(data) {
    //do stuff with your data here
});

good luck :)

Rent Charter Buses Company
READ ALSO
How to do ajax PATCH?

How to do ajax PATCH?

I am trying to do ajax PatchBut it's not working

117
Change .html URL depending on the active div

Change .html URL depending on the active div

I have two html pages: index1html and index2

92
Back button of the browser is not working + content is not loading if don&#39;t click on refresh button

Back button of the browser is not working + content is not loading if don't click on refresh button

I am really new to JS/jQuery/Ajax I have this codeI want that the content in article tag change but to keep all the rest (header, menu and footer) stays the same while the user click on a link of on the website

106
`element.innerHTML` not working as expected

`element.innerHTML` not working as expected

I have a form on whose submission, will post a URL, and the server returns a HTML string which should be appended to the form

97