Ajax using jQuery

Continuing on from Ajax 101, it's time to simplify things with jQuery. To load the contents of the file data.txt into a div with id content, we use:

  $('#content').load('data.txt');

To load structured data, we need to use the getJSON method. Below is an example which logs the data from the JSON file to the console:

  $.getJSON('ajax.json', function(data) {
  	console.log(data);
  });

Then we loop through the objects returned from the JSON data with the jQuery each method.

  $.getJSON('ajax.json', function(data) {
	var output = '<ul>';
	$.each(data, function(key,value) {
		output += '<li>' + value.name + '</li>';
	})
	output += '</ul>';
	$('#content').append(output);
  });

Comments are closed.