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
jQuery load() Method
jQuery Ajax: ajax(), get(), post() and getJSON()
jQuery Deferred, Promises and $.when()
Exercises & Assignments
Write jQuery code to load JSON data with Ajax and show it in a list
Write jQuery code to submit a form with Ajax
Interview Questions & Answers
How do you make an Ajax call in jQuery?
What is the difference between $.get(), $.post() and $.ajax() in jQuery?
What are Deferred objects and promises in jQuery?
How do you handle Ajax errors in jQuery?