AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 227


$(document).ready(function(){
$("#requestButton").click(function(){sendRequest();});
});
</script>
</head>
<body>
<form action="#" method="get">
<input id="requestButton" type="button" value="Say Hello" />
</form>
<br /><br />
<div id="responseOutput"> </div>
</body>
</html>

NNOT EOTE jQuery will automatically add in a request header, X-Requested-With: XMLHttpRequest.
Inspection of the source code version 1.1.3 shows that this is hard coded in at the moment.

jQuery Ajax Conveniences

Because jQuery aims for short and simple statements, it provides a number of conveniences
for issuing Ajax requests. Rather than using $.ajax(), consider using $.get() or
$.post() to trigger a GET or POST Ajax request. The basic syntax of each is similar:

$.get(URL,params,callback)
$.post(URL,params,callback)

The URL parameter will simply be a string containing the URL to invoke; the parameters
value should be an object literal of the parameters to be passed either via query string, in the
case of a GET request, or via request body, in the case of a POST. The callback value is a
function to invoke upon successful data receipt and will receive a single parameter that is the
data provided by the response. Given these new functions, swap out the $.ajax() method in
the first example for something like this:

$.get("http://ajaxref.com/ch1/sayhello.php",
function(data){handleResponse(data);});

The library provides even more data specific helper functions. For example,
$.getJSON(URL,params,callback) fetches JSON using the GET method from the
specified URL. It is really just an extension to $.get() where you indicate the data type
desired. Similarly, $.getScript(URL, callback) is provided. It is the same thing as
using $.get(), though given that JavaScript code is returned, it will be executed upon
return. However, people who are concerned about specific data type handling will likely
resort to using the full $.ajax() method where they can have a bit more control. Finally,
to support direct consumption of HTML or text responses into the page, jQuery provides
the load() method with the following syntax:

load(url,params,callback)

where url is the URL to fetch via GET, params is an object of name-value pairs of
parameters to send to the URL if needed, and callback is an optional function to be called
Free download pdf