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?
Open a connection and specify if you are sending(POST) or receiving(GET) data using POST/GET and the URL where the JSON data file is located. Specify what function or tasks to perform once the connection is LOADED. Send the request to the server.
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
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);
});
The most efficient way is to use plain JavaScript:
var a = new XMLHttpRequest();
a.open("GET","your_json_file",true);
a.onreadystatechange = function() {
if( this.readyState == 4) {
if( this.status == 200) {
var json = window.JSON ? JSON.parse(this.reponseText) : eval("("+this.responseText+")");
// do something with json
}
else alert("HTTP error "+this.status+" "+this.statusText);
}
}
a.send();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With