简体   繁体   中英

jQuery loop with JSON data

I'm sending some JSON data to an Ajax function, this is what the data looks like:

{"one": 21, "two": 10, "three": 19, "four": 100}

Using jQuery, I would now like to show this data inside an <h3> tag. For example, I would like to have all the one, two, ... on one side. Here is what I tried:

 $.ajax({
  url: $("#container").attr("data-url"),
  dataType: 'json',
  success: function (data) {
    $.each(data, function(key, val) {
        $('#test').text(key);
    });
  }
});

Html

<h3 id="test"></h3>

The problem with this code is that it only shows the first occurrence of the array, in this case, I will only see " one ". Can someone help me find what I'm doing wrong?

You're overwriting the element each time through the loop. You need to concatenate all the keys and then put that in the element.

success: function(data) {
    var text = Object.keys(data).join(', ');
    $('#test').text(text);
}

You're overwriting the key in each loop. You need to add all them to a variable then print that. Since you want them all on one side (which is vertically), then you need to separate them by line breaks and add them using html() instead of text() ;

var t = '';
$.each(data, function(key, val) {
    t += key + '<br/>';
});
$('#test').html(t);

I assume you want the values too on the other side. Let's say you want to separate the keys and values by the equal sign:

var t = '';
$.each(data, function(key, val) {
    t += key + ' = ' + val + '<br/>';
});
$('#test').html(t);
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
    $.each(data, function(key, val) {
        $('#test').append(key + ', ');
    });
}
});

Just use $('#test').append instead of $('#test').text to keep the keys added previously

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