简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM