cluther
cluther

Reputation: 421

Iterate over JSON to dynamically create multiple JQuery Mobile Pages

I'm learning JQuery mobile and to help me down the path I'm seeking an example problem solution. I'd like to iterate over a JSON query to dynamically create multiple pages within a single HTML page (see multipage http://jquerymobile.com/test/docs/pages/multipage-template.html). Ideally, each page would have a forward and back button to advance/regress through the JQuery mobile pages.

UPDATE: What I have so far;

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Get JSONP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" />
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
  <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
 </head>
<body>
<div id="target">
<script>
// best to put this code in an external .js file
var loadtwitter = function() {

  $.getJSON('http://search.twitter.com/search.json' + '?q=jquery&callback=?', function(data) {
     $.each(data.results, function(index, value) {
       var o1 = "<div data-role='page' id='page" + index +"' data-title='Twitter Item " + index +"'>";
       var o2 = "<div data-role='header'><h1>Item " + index + "</h1></div>"; 
       var o3 = "<div data-role='content'><p>" + value.text + "</p>";
       var o4 = "<a href='#page" + (index - 1) + "' data-role='button' data-inline='true' data-icon='arrow-l'>Previous</a>";
       var o5 = "<a href='#page" + (index + 1) + "' data-role='button' data-inline='true' data-icon='arrow-r'>Next</a>";
       var o6 = "</div>";           
       var output = o1 + o2 + o3 + o4 + o5 + o6;  
       $('#target').append(output);
     });

    }); 
   $.mobile.changePage($("#page1"));
  };

  $(document).ready(loadtwitter);
 </script>
 </body>
</html>

Upvotes: 1

Views: 1433

Answers (1)

bensfromoz
bensfromoz

Reputation: 11

If you're using jquery mobile you shouldn't be relying on $(document).ready. you would be better off using the below pattern borrowed from the jQuery docs.

$(document).bind( "pagebeforechange", function( e, data ) {
            loadtwitter();
            e.preventDefault();
        }
    }
});

Upvotes: 1

Related Questions