BarclayVision
BarclayVision

Reputation: 863

Create AJAX call to display any simple key/val JSON

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"}]

Upvotes: 1

Views: 302

Answers (2)

tymeJV
tymeJV

Reputation: 104795

Use $.each to iterate through JSON, you can create a generic function to handle it:

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

Demo: http://jsfiddle.net/9z4VH/

Upvotes: 0

dorphalsig
dorphalsig

Reputation: 711

Create your HTML something like:

<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>

Then parse your JSON and for each data line you have to clone hiddenDiv, and change the values of label and input using your favorite selector, then append to $(".listViewUl").

The loop would be something like:

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

as long as the source for cloning is hidden (so it wont bother anybody) and out of any form (so it wont mess up your server code), you can play with it however you want, once you're happy, you clone it and append it where you want to do it.

... Why can't medicine be this way?

Upvotes: 1

Related Questions