1

Currently I am getting data from a mysql database using jquery, but I would like to know how to create content for my webpage based on the data that is received. For example, if I return a JSON object like { "options" : 3 }, then I would like to know how to respond accordingly in the HTML to create 4 list item.

    for (i = 0; i < 3; i++){
    $('ul#optionsList').append('<li><a href="javascript:void(loadRand());">1.</a>          </li>');
        }

jQuery Mobile ListView

    <ul id="optionsList" data-role="listview" data-theme="g">
        </ul>

Thank you in advance.

Apollo
  • 8,874
  • 32
  • 104
  • 192

2 Answers2

2

You have many possibilities how to create and modify DOM elements, here is jsFiddle example that populates unordered list

For more information about creating new elements see

And for better architecture of your page you might consider to use libraries such as Backbone.js (with comprehensive beginner tutorial here)

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
cek-cek
  • 470
  • 8
  • 13
  • +1 OP, make sure you are not transmitting any sensitive information via JSON object. Better solution IMO would be to use PHP. [See this question](http://stackoverflow.com/questions/2256310/directly-accessing-server-database-via-ajax-without-php-or-some-other-intermedi) – Alen Jul 22 '12 at 21:57
  • 1
    @cek-cek your JSFiddle ex is great, however I'm using jQuery Mobile and the styling for my ListView disappears when I try to append using your code...I have edited my question above with the code I'm using. – Apollo Jul 22 '12 at 22:31
  • After inserting new list items you have to call `$('ul#optionsList').listview('refresh');` to apply proper jQuery item styling. Here is jsFiddle: http://jsfiddle.net/xLmdw/ – cek-cek Jul 22 '12 at 22:56
0

If you required to built a huge html with your data, consider using templates. handlerbars.js is a very good choice. http://handlebarsjs.com/