jQuery load() Method
Ajax lets a page get data from the server without a reload. The easiest Ajax method of jQuery is load(): it gets HTML from a file and puts it inside the selected element.
Syntax
$(selector).load(url, data, callback)
Example
We have a file menu.html on the same server:
<ul>
<li>Home</li>
<li>Courses</li>
<li>Contact</li>
</ul>
<div id="menu-area">Loading...</div>
$('#menu-area').load('menu.html', function (response, status) {
console.log('Status: ' + status);
});
Console output
Status: success
HTML after the code runs
<div id="menu-area">
<ul>
<li>Home</li>
<li>Courses</li>
<li>Contact</li>
</ul>
</div>
Load only a part of the file
Add a space and a selector after the URL. jQuery loads the whole file, and puts only the matching part in your element.
<html><body>
<h1>Welcome page</h1>
<div id="news"><p>Latest news here</p></div>
<div id="ads">Ad</div>
</body></html>
<div id="box"></div>
$('#box').load('page.html #news');
HTML after the code runs
<div id="box">
<div id="news">
<p>Latest news here</p>
</div>
</div>
Handle errors in the callback
<div id="box">Old content</div>
$('#box').load('missing.html', function (response, status, xhr) {
if (status === 'error') {
console.log('Error: ' + xhr.status + ' ' + xhr.statusText);
$('#box').text('Sorry, the content could not be loaded.');
}
});
Console output
Error: 404 Not Found
HTML after the code runs
<div id="box">Sorry, the content could not be loaded.</div>
Important points
- The file must come from the same origin (same domain, port and protocol), unless the other server allows it with CORS.
- A page opened as a local file (
file://) does not work in most browsers. Test with a local web server. - Scripts inside the loaded HTML are run by
load(), so only load files which you trust. - Do not use
load()for JSON data. Use$.getJSON(). See jQuery Ajax.
Note:
load() is good for simple things like including a menu or a part of a page. For all other needs, use $.ajax() or the shortcut methods. Next: jQuery Ajax.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |