how to loop through json array in jquery?

前端 未结 8 555
温柔的废话
温柔的废话 2020-12-09 09:03

I have a php page from which I get response in json:

[{\'com\':\'something\'},{\'com\':\'some other thing\'}]

I want to loop it and append

相关标签:
8条回答
  • 2020-12-09 09:25

    Your array has default keys(0,1) which store object {'com':'some thing'} use:

    var obj = jQuery.parseJSON(response);
    $.each(obj, function(key,value) {
      alert(value.com);
    }); 
    
    0 讨论(0)
  • 2020-12-09 09:26

    try this

    var events = [];
    
    alert(doc);
    var obj = jQuery.parseJSON(doc);
    
         $.each(obj, function (key, value) {
    
        alert(value.title);
    

    });

    0 讨论(0)
  • 2020-12-09 09:31
    var data=[{'com':'something'},{'com':'some other thing'}];
    $.each(data, function() {
      $.each(this, function(key, val){
        alert(val);//here data 
          alert (key); //here key
    
      });
    });
    
    0 讨论(0)
  • 2020-12-09 09:31

    Try this:

    for(var i = 0; i < data.length; i++){
        console.log(data[i].com)
    }
    
    0 讨论(0)
  • 2020-12-09 09:40

    You are iterating through an undefined value, ie, com property of the Array's object, you should iterate through the array itself:

    $.each(obj, function(key,value) {
       // here `value` refers to the objects 
    });
    

    Also note that jQuery intelligently tries to parse the sent JSON, probably you don't need to parse the response. If you are using $.ajax(), you can set the dataType to json which tells jQuery parse the JSON for you.

    If it still doesn't work, check the browser's console for troubleshooting.

    0 讨论(0)
  • 2020-12-09 09:42

    you can get the key value pair as

    <pre>
    function test(){    
    var data=[{'com':'something'},{'com':'some other thing'}];    
    $.each(data, function(key,value) {    
    alert(key);  
    alert(value.com);    
    });    
    }
    </pre>
    
    0 讨论(0)
提交回复
热议问题