Reputation: 501
Well, I have created an API and the output from http://localhost/lsapp4/public/api/articles in Postman is as follows:
{
"data": [
{
"id": 1,
"title": "Demo Article-1",
"body": "Happy Holidays1"
},
{
"id": 2,
"title": "Demo Article-2",
"body": "Happy Holidays2"
},
{
"id": 3,
"title": "Demo Article-3",
"body": "Happy Holidays3"
}
],
"links": {
"first": "http://lsapp4.test/api/articles?page=1",
"last": "http://lsapp4.test/api/articles?page=2",
"prev": null,
"next": "http://lsapp4.test/api/articles?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 2,
"path": "http://lsapp4.test/api/articles",
"per_page": 3,
"to": 3,
"total": 4
}
}
How can I parse the title and body iteratively? I tried to do it like:
$.getJSON("http://localhost/lsapp4/public/api/articles",function(regen){
var i=0;
$.each(regen,function(index,item)
{
alert(item[i].title);
i=i+1;
});
});
But it did not work.
Upvotes: 0
Views: 30
Reputation: 2162
Your API is returning an object that contains an array in a field called data. You need to perform the $.each
on this data field. You also do not need to reference i
in the call to item.title
. See sample code below:
var regen = {
"data": [{
"id": 1,
"title": "Demo Article-1",
"body": "Happy Holidays1"
},
{
"id": 2,
"title": "Demo Article-2",
"body": "Happy Holidays2"
},
{
"id": 3,
"title": "Demo Article-3",
"body": "Happy Holidays3"
}
],
"links": {
"first": "http://lsapp4.test/api/articles?page=1",
"last": "http://lsapp4.test/api/articles?page=2",
"prev": null,
"next": "http://lsapp4.test/api/articles?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 2,
"path": "http://lsapp4.test/api/articles",
"per_page": 3,
"to": 3,
"total": 4
}
}
// Omitted $.getJSON for testing and demo purposes.
// Corrected code is also below.
$.each(regen.data, function(index, item) {
alert(item.title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Corrected $.getJSON
call:
$.getJSON("http://localhost/lsapp4/public/api/articles",function(regen){
$.each(regen.data, function(index,item)
{
alert(item.title);
});
});
Upvotes: 1