How to populate a jQuery Mobile list view with JSON data from server?

ajax, cordova, jquery-mobile, json, listview

Solution

Have a look at the jQuery.getJSON() method on w3schools and jQuery API.

Example from jQuery API:

$.getJSON('ajax/test.json', function(data) {
  var items = [];

  $.each(data, function(key, val) {
    items.push('<li id="' + key + '">' + val + '</li>');
  });

  $('<ul/>', {
    'class': 'my-new-list',
    html: items.join('')
  }).appendTo('body');
});

This example, of course, relies on the structure of the JSON file:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.

Problem

I'm using jQuery Mobile with PhoneGap. How can I pull JSON data (from a server) and populate it into a list view.

Original source