(^190) ❘ CHAPTER 7 AJAX
function()
{
$.getJSON(
'Example 7-2/' + this.value + '.json',
function(json)
{
// Swap out the flag image
$('div#addressCountryWrapper img').attr({
alt : json.name,
src : 'flags/' + json.iso2.toLowerCase() + '.png'
});
// Remove all of the options
$('select#addressState').empty();
// Set the states...
$.each(
json.states,
function(id, state)
{
$('select#addressState').append(
$('')
.attr('value', id)
.text(state)
);
}
);
// Change the label
$('label[for="addressState"]').text(
json.label + ':'
);
}
);
}
);
$('select#addressCountry').click();
}
);
In the preceding JavaScript, things function similarly to the example that you saw in the last sec-
tion where the server response was formatted as XML. However, this time you initiate an AJAX
request using the $.getJSON() method instead of the $.get() method. Figure 7-2 shows
the results.
These two methods are similar, except that you don’t have to specify the last argument, specify-
ing the format of the server response with the $.getJSON() method. Another difference is that you
are requesting a fi le with a .json extension instead of .xml. Also, like in the last example, the fi le
requested depends on which country is selected from the drop-down menu. The JSON object is
formatted like so in the fi le being requested:
http://www.it-ebooks.info
elliott
(Elliott)
#1