简体   繁体   中英

How to consume json response in jQuery each

I try to append a country list in in html. there is a country name with id in my JSON response data. Please see my below image.

在此处输入图片说明

Here the 15 is country id and Brazil is country name. But I am clueless how to iterate the response array in $.each .

Try this:

var arr = [["15","Brazil"],["14","Italy"],["13","Spain"],["15","Scotland"]];

$.each(arr, function(key,obj){
    // obj contains array like : ["15","Brazil"]
    $('body').append('<div>id:'+obj[0]+', country:' + obj[1]+'</div>');
 })

http://jsfiddle.net/bSfT2/1/

As explained in JQuery manual you can iterate in your json with .each method:

$.getJSON( "ajax/myfile.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + val[0] + "'>" + val[1] + "</li>" );
  });
  $( "<ul/>", {
    "class": "countries",
    html: items.join( "" )
  }).appendTo( "body" );
});

Otherwise, if you have a string:

 var jsonData = [["15","Brazil"],["14","Italy"]];
 $.each(jsonData, function(key,val){
    $('#divID').append('<div>id:'+ val[0] + ', country:' + val[1] + '</div>');
 })

Here DEMO .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM