␡
- 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
This chapter is from the book
Recipe: Loading HTML Directly
Even simpler than the get() method is to use load() to gather a snippet of HTML and put it directly into the document. Listing 5.3 demonstrates how to do this.
Listing 5.3. Filling a <div> with a Dynamic HTML Snippet
00 <!DOCTYPE html> 01 02 <html lang="en"> 03 <head> 04 <title>The AJAX load() request</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"> 13 14 <script src="https://code.jquery.com/jquery-latest.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 $('#target').load('03a-test-snippet.html'); 23 24 }); 25 26 }); 27 </script> 28 </body> 29 </html>
The HTML that will be loaded into the document is as follows:
<h1>Hello world from external HTML snippet</h1>
Line 22 demonstrates how the load() function works directly on a selection of elements without requiring a callback handler.