0

I am very new to jquery. I have an api '/categories' which returns me json object of categories. Response is like in this format:

[
{
name: "Laptop deals",
slug: "laptop-deals",
imageURL: "image.jpg",
id: 1
},
{
name: "Fashion deals",
slug: "fashion-deals",
imageURL: "image.jpg",
id: 2
},
{
name: "Mobile deals",
slug: "mobile-deals",
imageURL: "image.jpg",
id: 3
},
{
name: "Home & Kitchen deals",
slug: "home-and-kitchen-deals",
imageURL: "image.jpg",
id: 4
},
]

I want to access this in my html view to display.I have tried this:

<script>
$(document).ready(function(){
$("button").click(function(){
    $.getJSON('/categories',function(data){
      $.each(function(obj,ind,data){
          $('#div').append(obj.slug);
      });
    });
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>

But it doesnt do anything when i click on button. I have tried previous post on stack overflow but nothing works

Amol Bais
  • 332
  • 1
  • 6
  • 30
Devendra Verma
  • 975
  • 2
  • 10
  • 24

1 Answers1

2

Change

$.each(function(obj,ind,data){
    $('#div').append(obj.slug);
});

into

$.each(data, function(i, item) {
    $('div').append(data[i].slug);
    //or
    //$('div').append(item.slug);
});​
Maths RkBala
  • 2,207
  • 3
  • 18
  • 21