jQuery Mobile Cookbook C5R9 - Dynamic Data List - AJAX

Example of populating a list using AJAX in jQuery Mobile author(s): Don Walter

HTML

<script src="http://jquery-json.googlecode.com/files/jquery.json-2.3.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.css">
<div data-role="page">

  <div data-role="header">
    <h1>Dynamic List - AJAX</h1>
  </div>

  <div data-role="content">

    <ul data-role="listview" id="myList"></ul>

  </div>

</div>

JavaScript

// The data that will be returned to your AJAX call
var data = {
  json: $.toJSON([
    "Ben Folds Five",
    "Cake",
    "Gomez",
    "Guster"
  ])
};

$( document ).ready( function() {
  $.ajax({
    url: "/echo/json/",
    type: "POST",
    dataType: "json",
    data: data,
    success: function(data) {
      // Set your list element into a variable
      var $myList = $( "#myList" );
      var newItems = [];

      // Loop through your results and append a new <li> onto your list for each result
      $.each( data, function( index, value ) {
        newItems.push( "<li><a href='index.html?id=" + index + "'>" + value + "</a></li>" );
      });

      // Append the new items to your list
      $myList.append( newItems.join( "" ) );

      // Refresh the listview to apply jQuery Mobile formatting to new items
      $myList.listview( "refresh" );
    }
  });
});