vendredi 4 décembre 2015

Simple get API call in jQuery

I have a url to which I need to make a get call. The url returns the following JSON response when run in POSTMAN.

{
  "status": true,
   "data": [
    {
      "id": 1,
      "suggestion": "shirt"
    },
    {
      "id": 2,
      "suggestion": "jeans"
    },
    {
      "id": 3,
      "suggestion": "puma"
    },
    {
      "id": 4,
      "suggestion": "spykar"
    }
  ],
  "lastPageNumber": 0
}

I need to get the "suggestion" key's value and append to my list. Following is my code to get the data and append its values to a list as shown.

jQuery.getJSON( url, function( response ) { 
          $.each(response.data ,function() {
            $.each(this, function (key, value) {
                if(key=="suggestion")               
                 $('#suggestions').append('<li class="suggestItem">' + '<a>' + value + '</a>' + '</li>');
            });
          });
    });

And this is the ul to which I have to append these list items.

  <ul id="suggestions" style="position: absolute; list-style-type: none;">

However, I do not seem to get any data in response or maybe I am not traversing through the JSON array correctly. So, I need help in whether I have written the right code or not.

Also additional information: I am running this project on localhost and the url is something http://ift.tt/1OLd4C8 so does this also affect (I read something about cross domain in ajax).




Aucun commentaire:

Enregistrer un commentaire