Write jQuery code to load JSON data with Ajax and show it in a list
Description: The file courses.json has a list of courses. Load it and show the titles in the list.
Hint:
- Use
$.getJSON()and$.each().
The JSON file and the HTML
[
{ "id": 1, "title": "HTML Basics" },
{ "id": 2, "title": "CSS Layouts" },
{ "id": 3, "title": "jQuery Tutorial" }
]
<ul id="courses"></ul>
Solution
$.getJSON('courses.json')
.done(function (courses) {
$.each(courses, function (i, course) {
$('<li>').text(course.title).appendTo('#courses');
});
})
.fail(function () {
$('#courses').text('Could not load the courses');
});
HTML after the code runs
<ul id="courses">
<li>HTML Basics</li>
<li>CSS Layouts</li>
<li>jQuery Tutorial</li>
</ul>
How it works
$.getJSON()loads the file and parses it into an array.- We create a list item with
.text()for each course. - The
fail()handler shows a message if the file cannot be loaded.
Read jQuery Ajax.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |