I’m getting this data dictionary from a db :
{"first":{"Head1":"6643Z","Head2":"1245Z"},"second":{"Head1":"1109E","Head2":"1231A"}}
and I need get only the first value for “Head1” record, for this I added a global var
in order to get the value out of the getJSON method, but run first the second alert
with a undefined value, and then run the first alert with the right value…
var message;
jQuery.getJSON("get_data.json", function(msg){
jQuery.each(msg,function (key,val){
message=val['string_data'];
return false;//trying to break
});
alert("first"+message);
});
alert("second"+message);
In order to this, how can I force have the right value on second alert, in other words,
how force to run the code in the right order….
The reason the second alert shows
undefinedis that when that code runs, the request hasn’t completed yet.You can make the
getJSONsynchronous, so that the alert doesn’t run until the request is complete, but it leads to poor user experience (locks up the browser) and jQuery will be dropping support for it in an upcoming version. If you look atgetJSONin the docs, you’ll see it’s just a wrapper that callsajax, and if you useajaxyou can specify anasync: falseoption. (Note that this is true because you’re using ajax with JSON; if it were JSON-P, you would have no synchronous option, as JSON-P is an asynchronous protocol.)Your much better option is to embrace the asynchronous nature of web communication, and whatever you have that needs to use this data, have it supply a callback:
Also note that the object you’re getting back has no order, so your code getting the “first” value from it will be unreliable. You’ll need to know the property key you’re looking for in order to reliably get the value for that property. The order in which they appear in the text of the JSON has no effect on the order of the properties in the resulting object. (Arrays would, of course, be different.)
So for instance, if you always want the value for
first, then: