Johann
Johann

Reputation: 447

Get external JSON files from javascript - local website

I would like to know if there is a way to get multiple external JSON files from a javascript file.

My website runs on a local machine. I have several JSON files on this machine :

file1.json :

{ "info1": "foo1", "info2": "foo2", "info3": "foo3", "info4": "foo4"}

file2.json :

{ "info5": "foo5", "info6": "foo6", "info7": "foo7", "info8": "foo8"}

etc..

I would like to access these files in my website with javascript in order to perform a research.

Do you know a way to do this ?

Thanks for your help

Johann

Upvotes: 3

Views: 2063

Answers (2)

Headshota
Headshota

Reputation: 21439

you should send a request from javascript to your server and retrieve the output of the file. with jQuery you could do following:

jQuery.getJSON(url, function(data){
   // do something
});

Upvotes: 0

user529758
user529758

Reputation:

You can use AJAX for this:

function callback_function(object)
{
    // `object' contains the parsed JSON object
}

var xhr = new XMLHttpRequest();
xhr.open("GET", "/js/file1.json", true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        callback_function(JSON.parse(xhr.responseText));
    }
}
xhr.send();

Upvotes: 5

Related Questions