Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a JSON object from a file with ajax?

Tags:

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?

like image 706
rubo77 Avatar asked Jan 17 '13 21:01

rubo77


People also ask

How do I load a JSON file in AJAX?

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.

Can we get JSON file using AJAX?

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.

Which object can be used to retrieve data in AJAX?

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.


2 Answers

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);
});
like image 122
Denys Séguret Avatar answered Oct 19 '22 03:10

Denys Séguret


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();
like image 25
Niet the Dark Absol Avatar answered Oct 19 '22 01:10

Niet the Dark Absol