简体   繁体   中英

About getJSON function in jQuery

{
   "Adam":{
      "Math":"93",
      "Science":"96",
      "Email":"adam@example.com",
      "City":"NY"
   },
   "Tom":{
      "Math":"65",
      "Science":"56",
      "Email":"tom@example.com",
      "City":"LA"
   },
   "Joe":{
      "Math":"74",
      "Science":"83",
      "Email":"joe@example.com",
      "City":"Washington"
   }
}

Above is the JSON content present at the http: //ActualUrl/path.json

I am accessing the JSON file and filling the two arrays with name and marks in science with the code below.

     var names=[];
     var marks=[];
    $.getJSON("http://path.json",function(data){               
                $.each(data, function(key, val) {   
                     names.push(key);
                    // I placed alert the check the value key.
            marks.push(parseInt(val.Science));                  
                    });
                });
    alert(names.toString()); // names is found blank
    alert(marks.toString()); 

When I check the array at the end. Array is found blank. Why this wrong behaviour with getJSON ? I placed alert in the each and check the value. It returns correct value.

$.getJSON fires off asynchronously, meaning that in most cases it will not have completed by the time you read out your variables. You will need to restructure your solution such that you do the thing you want to do within it's success callback:

$.getJSON("http://path.json", function(data) {
    $.each(data, function(key, val) {
        names.push(key);
        marks.push(parseInt(val.Science));
    });

    // do your thing here.
});

Primary problem

You are filling your array in the async callback, but alert them right away. So, this is what happens:

  1. You execute ajax call. Request is sent to the server.

  2. You alert values of arrays. They are blank, since the server didn't reply yet.

  3. Server replies, your callback is fired and arrays are filled. Too late.

Solution:

Put alert logic to the callback.

Other notes

jQuery.each is for iterating collections. You, on the other hand, have an object (or dictionary).

Try this code:

for(key in data) {
  names.push(key);
  var val = data[key];
  marks.push(parseInt(val.Science));                  
}

for ... in ... construct iterates object properties, which is what you want.

$.each Description: Iterate over a jQuery object, executing a function for each matched element. (from: http://api.jquery.com/each/ )

The returned JSON is not a jQuery object, just a plain JavaScript object. Use foreach(key in data) instead.

Oh and move the alert() inside the callback function :)

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