Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 825
Johann Avatar asked May 11 '26 09:05

Johann


1 Answers

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();