jQuery - AJAX load() method
jQuery load() method
The jQuery load() method is a simple but powerful AJAX method.
The load() method loads data from the server and puts the returned data into the selected element.
Syntax:
$
(
selector
)
.
load
(
URL
,
data
,
callback
)
;
Required URL The parameter specifies the URL you wish to load.
Optional data The parameter specifies a set of query string key/value pairs to send with the request.
Optional callback The parameter specifies the name of the function to be executed when the load() method completes.
This is the content of the sample file ("demo_test.txt"):
<
h2
jQuery AJAX is a great feature!
h2
<p id="p1">This is some text in a paragraph.
p
The following example loads the content of the file "demo_test.txt" into the specified
Example
$
(
"
#div1
"
)
.
load
(
"
demo_test.txt
"
)
;
Try it »
You can also add a jQuery selector to the URL parameter.
The following example loads the content of the element with id="p1" from "demo_test.txt" into the specified
Example
$
(
"
#div1
"
)
.
load
(
"
demo_test.txt #p1
"
)
;
Try it »
The optional callback parameter specifies a callback function to run when the load() method completes. The callback function can take different parameters:
- responseTxt - contains the result content on success
- statusTXT - contains the status of the call
- xhr - Contains the XMLHttpRequest object
The following example shows a message box after the load() method completes. If load() succeeded, it shows "External content loaded successfully!", and if it fails, it shows an error message:
Example
$
(
"
button
"
)
.
click
(
function
(
)
{
$
(
"
#div1
"
)
.
load
(
"
demo_test.txt
"
,
function
(
responseTxt
,
statusTxt
,
xhr
)
{
if
(
statusTxt
==
"
success
"
)
alert
(
"
External content loaded successfully!
"
)
;
if
(
statusTxt
==
"
error
"
)
alert
(
"
Error:
"
xhr
.
status
"
:
"
xhr
.
statusText
)
;
}
)
;
}
)
;
Try it »