好了,我已经创建了一个接口,Postman中的http://localhost/lsapp4/public/api/articles的输出如下:
{
"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
}}
如何迭代地解析标题和正文?我试着这样做:
$.getJSON("http://localhost/lsapp4/public/api/articles",function(regen){
var i=0;
$.each(regen,function(index,item)
{
alert(item[i].title);
i=i+1;
});
});但它并没有起作用。
发布于 2021-01-03 09:00:48
您的API将返回一个对象,该对象在名为data的字段中包含一个数组。您需要在此数据字段上执行$.each。您也不需要在调用item.title时引用i。参见下面的示例代码:
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>
已更正$.getJSON调用:
$.getJSON("http://localhost/lsapp4/public/api/articles",function(regen){
$.each(regen.data, function(index,item)
{
alert(item.title);
});
});https://stackoverflow.com/questions/65545486
复制相似问题