How to use JavaScript to load and parse a static JSON file on a server

I am just starting to use javascript and json.

I need to read data (getInformation function) from a json file when processing an event in a javascript function. So I need it to be in sync. I don’t know if there is not enough code in the code, or I need to create a request and handle the callback, or I need to import additional javascript to use json. Because I don’t know how to make it work. This does not work, because at the end the array is empty. Any help is appreciated.

Json file:

{"Users": [
    {"Name": "Jane",
        "Points": 67,
        "age": 23},
    {
        "Name": "Sam",
        "Points": 65,
        "age": 21}
]} 

Option 1 - A function called by another function that processes the event:

var getInformation = function() 
{
    var path = "./data/users.json";
    var informationArray= [];
    console.log("Loading ....");
    $.getJSON(path, function(data) 
    {
        $.each(data, function(key, val) 
        {
            informationArray.push(key + '-' + val);
        });
    }); 
    return informationArray; 
}

Option 2 - A function called by another function that processes the event:

var getInformation = function() { 
var path = "./data/users.json";
var informationArray= [];
$.ajax({
         url: path,
         async: false,
         dataType: 'json',
         success: function(response) {
         $.each(response.items,
         function(item) {
         informationArray.push(item);
         });
         informationArray.push("success");
         }
         }); 
   return informationArray; }

, , . , - .

: $getJSON, ?

+5
2

JavaScript , AJAX JSON. AJAX , . jQuery. jQuery - - :

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>

script html - :

$.ajax({
  url: "data/users.json",
  dataType: "json",
  success: function(response) {
    $.each(response.Users, function(item) {
      informationArray.push(item);
    });
    informationArray.push("success");
  }
});

. http://api.jquery.com/jQuery.ajax/

+5

JSON ( ), :

var url = 'http://yoursite.com/data/users.json';
var j = [];
$.ajax({
  type: 'GET',
  url: url,
  dataType: 'json',
  success: function(data) { j = data;},
  async: false
});

alert(j.Users[0].Name);
0

All Articles