Tomuke
Tomuke

Reputation: 879

Populating jQuery Mobile ListView with local JSON data

I am trying to populate a JQM ListView with a local JSON information. However, no list items are created. Any help would be appreciated. Here is my code:

JSON File Structure:

[
{
"name" : "test"
"calories" : "1000"
"fat" : "100"
"protein" : "100"
"carbohydrates" : "800"
},
{
"name" : "test2"
"calories" : "10000"
"fat" : "343"
"protein" : "3434"
"carbohydrates" : "4343"
}
]

HTML:

<div data-role="page" data-title="Search" id="searchPage">
      <ul data-role="listview" data-inset="true" id="searchFood">
      </ul>
</div>

JS:

(Updated)

$(document).on("pageinit", "#searchPage", function(){
  $.getJSON("../JS/food.json", function(data){
        var output = '';
        $.each(data, function(index, value){
         output += '<li><a href="#">' +data.name+ '</a></li>';
        });
        $('#searchFood').html(output).listview("refresh");
  });
});

Upvotes: 2

Views: 8671

Answers (1)

Omar
Omar

Reputation: 31732

First of all, the return JSON array is wrong, values (properties) should be separated by commas.

var data = [{
    "name": "test",
        "calories": "1000",
        "fat": "100",
        "protein": "100",
        "carbohydrates": "800",
}, {
    "name": "test2",
        "calories": "10000",
        "fat": "343",
        "protein": "3434",
        "carbohydrates": "4343",
}];

Second mistake, you should read value object returned by $.each() function not data array.

$.each(data, function (index, value) {
  output += '<li><a href="#">' + value.name + '</a></li>';
});

jQueryMobile only enhances the page once when it is loaded. When new data is added dynamically to the page, jQueryMobile must be made aware of the data for the data to be enhanced.

After extracting data from JSON array, append them then refresh listview to restyle newly added elements.

$('#searchFood').html(output).listview("refresh");

Demo

Upvotes: 6

Related Questions