简体   繁体   中英

Loading a JSON file into a javascript

 var myJSON ;
$.getJSON("../json.json",function(data){
    myJSON =data;
});

I have tried using $.getJSON() using jquery,however the data it returns is always null. I do not understand why. The path to the JSON file is correct.

This code should work if the path is correct... however if you are declaring myJSON outside of the callback function probably you are trying to use it outside... before the callback function has been called:

var myJSON; // why are you declaring that here?
$.getJSON("../json.json",function(data){
    myJSON =data;
    console.log('Within the callback function: '+myJSON);
});

console.log('Outside the callback function: '+myJSON) // this is ALWAYS null

JSON data isn't immediately available after you make a request.
$.getJSON returns before the data gets downloaded and just calls the provided callback when it's finished.

You need to do

$.getJSON("../json.json",function(myJSON){
    // do something with myJSON
});

If you really need a synchronous request, use $.ajax with the parameter async to false .

Also check if your JSON is valid. There is a difference, how you can define arrays and objects in JavaScript and what is proper JSON.
eg [1,2,3,] should be [1,2,3] , {one:1} should be {"one":1} .

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