So now we'll bring Ajax into the picture by requesting data from the server. The server will return the seasons JSON data, and we will then pass array of seasons to our function that will create the unordered list.
The jQuery library makes working with Ajax requests very easy. jQuery has a getJSON
method that makes requesting and receiving JSON data from the server easy. In the simplest case, we'll pass two parameters when we use the getJSON
method: a URL that will be requested, and a "callback" function that will be called on a successful retrieval of JSON data. A simple case where we make a JSON request to the url "seasons.json" and simply log the data to the JS console looks like:
$(document).ready(function(){
$.getJSON("seasons.json",function(data) {
console.log(data);
});
});
"seasons.json"
function(data){ console.log(data); }
data
is the data from the JSON request.Example of getJSON in JSFiddle
So we take our previous example, where we built a list from a JSON data structure, and change it so that the JSON data comes from an Ajax request (using the getJSON
) method of jQuery:
Copyright © David Heitmeyer