Populating jQuery Mobile ListView with local JSON data

寵の児 提交于 2019-12-17 06:56:34

问题


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");
  });
});

回答1:


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



来源:https://stackoverflow.com/questions/21881830/populating-jquery-mobile-listview-with-local-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!