I have problem understanding arrays and loops, therefore this task is a bit confusing to me. Here's my stuff;
JSON
{
"states": [
    { 
        "name":"johor" , 
        "command":"view_johor" }, 
    { 
        "name":"selangor" , 
        "command":"view_selangor" }, 
    { 
        "name":"melaka" , 
        "command":"view_melaka" }, 
    { 
        "name":"kuala lumpur" , 
        "command":"view_kl" }, 
    { 
        "name":"penang" , 
        "command":"view_penang" }
    ]
}
JAVASCRIPT
$(function(){
$.ajax({
    type        :   'GET',
    url         :   'scripts/list.json',
    async       :   false,
    beforeSend  :   function(){/*loading*/},
    dataType    :   'json',
    success     :   function(result){
                        $.each(result, function(index, val){
                            for(var i=0; i < val.length; i++){
                                var item = val[i];
                                console.log(item.name)
                                }
                        });         
                        },
   });
});
My problem is I don't know how to use the loop it so that my HTML will return like this:
<ul>
   <li><a href="#view_johor">Johor</a></li>
   <li><a href="#view_selangor">Selangor</a></li>
   <!-- and so on, dynamically depending on json... -->
</ul>
I can access the data via console.log(item.name) and such, but I can't manipulate the data so that it will display like I wanted. I don't even know the term to use to search for questions, as I know this is like basic array stuff....Thank you in advance for your help!
JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);
JSON array are ordered list of values. JSON arrays can be of multiple data types. JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma.
JSON is built on two structures:An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
u can do it :
 $(function(){
$.ajax({ 
  type : 'GET', 
  url : 'scripts/list.json', 
  async : false, 
  beforeSend : function(){/*loading*/},
  dataType : 'json', 
  success : function(result){
   var buffer="";
    $.each(result, function(index, val){ 
      for(var i=0; i < val.length; i++){ 
        var item = val[i]; 
        console.log(item.name);
        buffer+=" <li><a href='#"+item.name+"'>"+item.name+"</a></li> <li><a href='#"+item.command+"'>"+item.command+"</a></li>"; 
      } 
      $('ul').html(buffer);
    });
  }
 });
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With