Web Development with jQuery®

(Elliott) #1

Making a Server Request (^) ❘ 189
countryId : 223,
iso2 : 'US',
iso3 : 'USA',
label : 'State'
},
function(xml)
{
// snip
},
'xml'
);
The new argument comes after the fi lename and before the function reference, and this is an object
literal that contains the data you want to pass along in the GET request to the server. In the preced-
ing example, I’ve modifi ed the fi lename to be simply Example 7-1/38.xml, and I’ve created an object
literal with four properties, countryId, iso2, iso3, and label. So, behind the scenes, this modifi ca-
tion will cause the request to the server to look like this:
Example%207-1/38.xml?countryId=223&iso2=US&iso3=USA&label=State
jQuery takes the items in the object literal and builds a GET request from them. Because GET
requests include data as part of the URL that you are calling, that data gets appended to the end
of the URL. The question mark in the URL indicates that what follows is GET request data; then
values are passed in name/value pairs, where each name and value is separated by an equals sign.
Then if there is more than one value, additional values are appended subsequently by appending
an ampersand character to the last name/value pair. Then this data is encoded for transport to the
HTTP server. When at the HTTP server, how this data is accessed depends on the server-side
language that you’re using to read it.
Requesting JSON Formatted Data
This section revisits the example from the last section but this time uses JSON as the format for data
transport instead of XML. I could use the same jQuery method, $.get(), to do this and change the
last argument from 'xml' to 'json', but jQuery offers another method called $.getJSON() for retriev-
ing JSON-formatted data. This method is just like the $.get() method except that the data format
returned by the server is obviously expected to be JSON.
Using JSON as the data transportation format makes the code even leaner and easier to work
with than XML, in addition to signifi cantly reducing the size of the response from the server. The
following example is the same example that you saw in the last section where when you select
Canada, the United States, or the United Kingdom from the drop-down, the fl ag, administrative
subdivisions, and administrative subdivision label all swap out, presenting data relevant to the
country you’re looking at. The HTML portion remains the same, and just a few modifi cations
are made to the JavaScript portion. This example is available in the source code materials as
Example 7-2.
$(document).ready(
function()
{
$('select#addressCountry').click(
http://www.it-ebooks.info

Free download pdf