Reputation: 45
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?
Upvotes: 2
Views: 4686
Reputation: 4936
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.
Upvotes: 9