Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load json from external file

I've never touched on JSON, but I just need some bits clearing up so that I can research how to solve my problem properly.

I have -HTML file -JS file -JSON file. All are linked in the html file.

My challenge is to load the JSON file and add together some of the values that are located within it. So far I'm struggling to find anything other than JQuery to open it... I can find things about parsing, but many examples use code inline and i'm lost as to whether they're coding on the js file or the JSON one!

I'm seeing AJAX mentioned too, but i plead ignorance to its use so far (i'm very new to JS). so, what would you recommend to load it? what should i research to see about obtaining the values and creating additions with them?

like image 768
Leah Thompson Avatar asked Feb 14 '26 15:02

Leah Thompson


1 Answers

Loading a JSON file:

jQuery:

$.getJSON('/my/url', function(data) {
  console.log(data);
});

Non-jQuery:

request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Success!
    var data = JSON.parse(request.responseText);
    console.log(data);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

note the console.log prints the contents of the JSON file to the javascript console. You can do whatever you want with the "data" variable.

like image 138
Austin Pray Avatar answered Feb 17 '26 04:02

Austin Pray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!