0





13

Advertisement

I have this .json file and I want to load it in a global variable that I can access from all web using AJAX, JavaScript. How can I do it? I want to access the variable by the index, for example my_var[1].img. I read a lot of posts but I didn't find the solution.

myData.json

{
 "data": [
 { "img": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRHQ5Sf2Cffo0QdRtFw0t8zdk90FWgywc1kDKAuOV874zYO_0pC", "other": "Ra.One" },
 { "img": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQkVg9n2UbPTeiPNGUOw2SqdAzJsZzuHrkYw78sjaMMCcTWcuFjUtT3NZ8", "other": "3 Idiots" },
 { "img": "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ0Wam0d96ASpEHDFfskGTBdILKlDpXAKzELFdfdKmkoye5JmrF9qS1u1qtZw", "other": "Chaalis Chauraasi (4084)" },
 { "img": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSAf7q-m96JL88_W8EATmVlwCfOKb5dw1keyDSO6PWwzaSVtqGyix2lvE", "other": "Gangs Of Wasseypur" }
 ]}

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyWeb</title>

 <script type="text/javascript" src="myData.json"></script>
 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

 </head>
 <body>

<script>
 var my_json;
 $.getJSON("myData.json", function(json) {
 my_json = json;
 });
</script>
</body>
</html>
Question author Joan-triay | Source

Advertisement


0


Given that jQuery.getJSON is an asynchronous function, you have to use the data inside your callback. If you want to save it in a global variable, just remember that you still have to use a function, called by the callback of getJSON, to use it (altough I wouldn't recommend it). Given your JSON structure, you can access the images with json.data[index].img, and create the global variable like this my_json = json.data to use it later like this my_json[index].img. Here's an example:

var my_json;

function useTheData() {
    for (var i = 0; i < my_json.length; i++) {
        console.log(i, "-", my_json[i].img);
    }
} 

$.getJSON("myData.json", function(json) {
    my_json = json.data;
    useTheData();
});

If you want to access your variable in the body of your script (i.e. not inside another function), then the only thing you can do is to use a synchronous request created with XMLHttpRequest, like this:

var xhr = new XMLHttpRequest(),
    my_json;

xhr.open('GET', 'myData.json', false);
xhr.send();

my_json = JSON.parse(xhr.responseText).data;

// Now use the my_json variable anywhere you want

Beware that this will slow down your script and halt the rendering and execution of your page until the request is finished, so I don't really recommend doing this.

Answer author Marco-bonelli