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 remend to load it? what should i research to see about obtaining the values and creating additions with them?
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 remend to load it? what should i research to see about obtaining the values and creating additions with them?
Share Improve this question asked Nov 27, 2014 at 18:06 Leah ThompsonLeah Thompson 451 silver badge5 bronze badges1 Answer
Reset to default 9Loading 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.