Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
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="http://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.

  • + Share This
  • 🔖 Save To Your Account