English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The jQuery load() method is a simple but powerful AJAX method.
jQuery load()The method loads data from the server and puts the returned HTML into the selected element.
This method provides a simple way to asynchronously load data from a web server.
Thisload()The syntax of the method is:
$(selector).load(URL, data, callback)
Parameters:
URL-Specify the URL you want to request
data -(Optional) Specify a pure object or string to be sent with the request to the server
callback-(Optional) Specify the callback function to be executed after the load() method is completed
The following example loads the content of the file 'ajax_intro.txt' into the DIV element:
$("button").click(function(){ $("div").load("ajax_intro.txt"); });Test See‹/›
The following example loads the page 'ajax_post.html' and sends some otherData:
$("button").click(function(){ let data = {fname:"Seagull", lname:"Anna"}; $("div").load("ajax_post.php", data); });Test See‹/›
This is the appearance of the PHP file ("ajax_post.html"):
<?php echo "<p>Hello ".$_POST['fname']." ".$_POST['lname'].", How are u doing?</p>"; ?>
Request method:If theDataIf provided as an object, use the POST method. Otherwise, it is assumed to be GET.
OptionalcallbackParameter specificationload()Callback function to be executed after the method is completed.
The callback function can have different parameters:
response -Contains the result data in the request
status -Contains the request status ("success", "notmodified", "error", "timeout", or "parsererror")
xhr-Contains the XMLHttpRequest object
The following example loads the page 'ajax_post.html' and sends some other data and alert status messages:
$("button").click(function(){ let data = {fname:"Seagull", lname:"Anna"}; $("div").load("ajax_post.php", data, function(response, status){ alert(status); }); });Test See‹/›
The following example displays a notification when an Ajax request encounters an error:
$("button").click(function(){ let data = {fname:"Seagull", lname:"Anna"}; $("#success").load("wrong_file.php", data, function(response, status, xhr){ if(status == "error"){ let msg = "Sorry but there was an error: "; $("#error").html(msg + xhr.status + " " + xhr.statusText); } }); });Test See‹/›
jQuery load()The method also allows us to retrieve only a part of the document.
This can be simply achieved by appending a space and a jQuery selector to the URL parameter.
The following example loads the content of the element with ID 'table' from the file 'ajax_load.html' into the DIV element:
$("button").click(function(){ $("div").load("ajax_load.html #table"); });Test See‹/›
For a complete reference of AJAX methods, please visit ourjQuery AJAX Reference.