jQuery Load

The jQuery load() method is a simple way to load data from a server and place it into a selected element. It allows you to fetch and display data dynamically, reducing the need for full page reloads.

Key Topics

Basic Usage of load()

The load() method loads data from the server and places it inside the selected element.

$("#content").load("example.html");

Explanation: This code loads the content of example.html and inserts it into the element with the ID content.

Loading Partial Content

You can specify a selector to load only a part of the requested file.

$("#content").load("example.html #specific-section");

Explanation: This code loads only the content of the element with the ID specific-section from example.html.

Example: Using load()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Load Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="content"></div>
    <button id="loadButton">Load Content</button>

    <script>
        $(document).ready(function() {
            $("#loadButton").click(function() {
                $("#content").load("https://jsonplaceholder.typicode.com/posts/1", function(responseText, status) {
                    if (status === "success") {
                        alert("Content loaded successfully.");
                    } else {
                        alert("Failed to load content.");
                    }
                });
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to use the load() method to fetch and display content dynamically in a div when a button is clicked.

Key Takeaways

  • Dynamic Content Loading: Use load() to fetch and display data from external files without a full page reload.
  • Selective Loading: Specify a selector to load partial content from a file.
  • Error Handling: Implement callback functions to handle success or failure of the load operation.