(^192) ❘ CHAPTER 7 AJAX
method as the json argument. All the data that you see in the JSON-formatted document is avail-
able inside that json variable. You access the ISO2 information as json.iso2, the label as json.label,
and the states array as json.states. Using JSON, you’ve removed a step that would otherwise be
required if you were working with XML data, which is querying the data within the response; with
JSON, the data is fed directly to an object and is available immediately. Also note how much leaner
the JSON fi le is compared to the verbose XML document.
Like the $.get() method, if you want to pass data to the server, you can provide that data in the
same optional data argument.
$.getJSON(
'Example 7-2/38.json', {
countryId : 223,
iso2 : 'US',
iso3 : 'USA',
label : 'State'
},
function(json)
{
}
);
Making a POST Request
POST requests are identical to GET requests in jQuery, except for the name of the method. Instead
of $.get(), you use $.post(). Because a POST method request is reserved for modifying the state of
the data in some way, you’re probably more often than not going to want to pass some data along
with your POST request, and that data will probably come from a form of some kind. jQuery makes
it easy to grab form data and pass that along to the server. The method jQuery provides for this
is serialize(). The serialize() method takes data for the input elements that you specify (which
encompasses ,
elliott
(Elliott)
#1