1

looking for way to auto generate a listview for JQuery-Mobile from any json call. I assume I would load results into an array and iterate through for key/value and populate results to a ul with the li's created based on the numbers of results... can't figure out how to get length of the keys and then loop through them to populate <li> with the key and val. Would like to have it work without having to know any of the json values.

here is a starting point that is not working:

$(document).ready(function(){
$.getJSON("json_mdb.php", function(data){
     for (var i = 0; i < data.length; i++) {
        $.each(data[i], function(key, val) {
            //console.log(key + ":" + val); 
            $('#myUL').html("<li>" + key + " : " + val + "</li>");  
        });
      } 
});                 
});


<div data-role="page" id="index" data-theme="d">

<div data-role="content">   
<div id="inventory">
    <ul data-role='listview' id='myUL' data-inset='true' class='ui-listview ui-listview-inset ui-corner-all ui-shadow'>
    </ul>
</div>
</div>

</div>

Example JSON:

[{"LastName":"Doe","FirstName":"John","ID":"DJ0000"},{"LastName":"Doe","FirstName":"Jane","ID":"DA0000"}]
4

2 回答 2

1

创建您的 HTML,例如:

<div id='hiddenDiv'>
<ul><li>
    <label for='hiddenInput'></label>
    <input name='hiddenInput' type='text' />
</li></ul>
</div>
<form action="blah.php" method="post" class="coolFormCSSClass">
    <ul id='listViewUl' data-role="listview" ...>

    </ul>
</form>

然后解析您的 JSON,对于每个数据行,您必须克隆 hiddenDiv,并使用您喜欢的选择器更改标签和输入的值,然后附加到 $(".listViewUl")。

循环将类似于:

var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(arr, function() {

//do stuff to the label (like fill in the text,
// remove the class and set some properties)        
$(".hiddenDiv label").doSomethingReallyCool()
//do stuff to the input
$(".hiddenDiv input").doSomethingReallyCool2()

var clonedLee = $(".hiddenLi").clone().appendTo(".listViewUl");
    });

只要克隆源是隐藏的(所以它不会打扰任何人)并且没有任何形式(所以它不会弄乱你的服务器代码),你可以随心所欲地玩它,一旦你高兴,你就克隆它并将其附加到您想要执行的位置。

...为什么医学不能这样?

于 2013-10-14T19:02:14.060 回答
0

用于$.each遍历 JSON,您可以创建一个通用函数来处理它:

function handleJSON(arrObject) {
    for (var i = 0; i < arrObject.length; i++) {
        $.each(arrObject[i], function(key, val) {
            console.log(key + ":" + val);
        });
    }
}

演示:http: //jsfiddle.net/9z4VH/

于 2013-10-14T23:15:13.043 回答