jQuery in Action
236
CHAPTER 8
Talk to the server with Ajax
In this simple page, we create a button and instrument it to initiate a call to
$.get()
b
once it's clicked. The
GET
request is made to the server resource at
reflectData.jsp
(which returns a text snippet showing the values that were
passed to it as request parameters), specifying values for request parameters
a
,
b
,
and
c
. The callback is passed the fetched data and can do whatever it wants with
it. In this case, it merely issues an alert displaying that data.
When this
HTML
page is loaded into a browser and the button is clicked, we
see the display of figure 8.4.
If the response contains an
XML
document, the document will be parsed, and the
data parameter passed to the callback will be the resulting
DOM
.
XML
is great when we need its flexibility and our data is hierarchical in nature,
but it can be painful to digest. Let's see another jQuery utility function that's
quite useful when our data needs are more basic.
quite useful when our data needs are more basic.
8.3.2 Getting JSON data
As stated in the previous section, when an
XML
document is returned from the
server, the
XML
document is automatically parsed, and the resulting
DOM
is made
available to the callback function. When
XML
is overkill or otherwise unsuitable as
a data transfer mechanism,
JSON
is often used in its place; one reason is that
JSON
is easy to digest in client-side script. Well, jQuery makes it even easier.
For times when we know that the response will be
JSON
, the
$.getJSON()
utility
function automatically parses the returned
JSON
string and makes the resulting
Figure 8.4 The
$.get()
utility function fetches data from the server that we can
manipulate as we please, including only showing it in an alert.