- Recipe: Setting Up an Example Server in Node.js
- Recipe: Performing a GET Request
- Recipe: Loading HTML Directly
- Recipe: Handling the Result by Using Promises
- Recipe: Handling Server Errors
- Recipe: Catching Page-not-Found Results
- Recipe: Handling Page Redirects
- Recipe: Setting Request Timeouts
- Recipe: Passing HTTP Headers
- Example: Validating Form Input on the Server Side
- Recipe: Loading XML
- Recipe: Listening to AJAX Events
- Recipe: Reading JSONP from an External Server
- Summary
Recipe: Performing a GET Request
One of the simpler AJAX requests can be executed by using the shorthand method for GET. You can imagine performing a similar call for POST, PUT, and DELETE. Keep in mind that PUT and DELETE are not supported by all browsers, so it is wise to use GET and POST. Listing 5.2 shows the use of the get() method.
Listing 5.2. Fetching JSON Values by using the get() Shorthand Function
00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>The AJAX get() request function</title> 05 </head> 06 <body> 07 08 <h2>Press the button to perform the request.</h2> 09 10 <button id="trigger">GET</button> 11 <br> 12 <div id="target"></div> 13 14 <script src="https://code.jquery.com/jquery-1.7.2.min.js"></script> 15 16 <script> 17 // please externalize this code to an external .js file 18 $(document).ready(function() { 19 20 $('#trigger').click(function() { 21 22 $.get('02a-test-values.json', function(data) { 23 24 $('#target').append('The returned value is: ' + data.name); 25 26 }, 'json'); 27 }); 28 29 }); 30 </script> 31 </body> 32 </html>
Line 22 fetches the following JSON document:
{ "name": "Adriaan de Jonge", "email" : "adriaandejonge@gmail.com" }
When executed, this script returns the name of the author. In this example, the success handler function is a callback directly passed to the get() function. The last parameter passed in the get() is 'json'. This is an optional data-type parameter. In this instance, it informs jQuery that the data requested will be returned in JSON format. Later examples demonstrate an alternative approach for callback functions. If you use a web service or have some server-side logic set up to handle data coming in before handing back a response, you can pass an additional set of data to the server through the get() function. To learn more about sending data to the server by using get(), see the official documentation at http://api.jquery.com/jQuery.get/.