Devendra Verma Devendra Verma - 4 months ago 8
JSON Question

How to print json data on view page coming from Server

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

Answer

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);
});‚Äč