Search code examples
javascriptjsonapiget

Getting data from API with AJAX


I am trying to get data from API and display them using AJAX I have this code

 $(document).ready(function(){  
          $('.show').click(function(){     
          $.ajax({
           url: 'url',
           dataType: 'json',
           success: function(data) {
              var items = [];
              $.each(data, function(key, val) {

                items.push('<li id="' + key + '">' + val + '</li>');    

              });

              $('<ul/>', {
                 'class': 'interest-list',
                 html: items.join('')
              }).appendTo('body');

           },
          statusCode: {
             404: function() {
               alert('There was a problem with the server.  Try again soon!');
             }
           }
    });
    });
    });

I have this result:

[object Object],[object Object],[object Object],[object Object],

What must I fix in my code?


Solution

  • $.each iterates over the array, and key was the index of the array, and val was the entire object

    You could change this line of code

    items.push('<li id="' + key + '">' + val + '</li>');
    

    to

    var key = Object.keys(val)[0];
    items.push('<li id="' + key + '">' + val[key] + "</li>"); 
    

    to just get the first key directly. Here is the documentation for Object.keys.