Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  32] [ 6]  / answers: 1 / hits: 50876  / 12 Years ago, thu, january 17, 2013, 12:00:00

I am using JSON to transfer data.



What do I need in my HTML page to read a file with Ajax that only includes one JSON object into my script?



Do I need jQuery too, or is it possible to load that JSON file with Ajax?



Is it different on different browsers?


More From » ajax

 Answers
26

You don't need any library, everything is available in vanilla javascript to fetch a json file and parse it :



function fetchJSONFile(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}

// this requests the file and executes a callback with the parsed result once
// it is available
fetchJSONFile('pathToFile.json', function(data){
// do something with your data
console.log(data);
});

[#80791] Thursday, January 17, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reecep

Total Points: 141
Total Questions: 95
Total Answers: 113

Location: Finland
Member since Mon, Nov 8, 2021
3 Years ago
;