我正在尝试将Json数组中的内容从api显示到我的html中。我该怎么办?
这是我的Json数组。
{
page: 2,
per_page: 3,
total: 12,
total_pages: 4,
data: [
{
id: 4,
first_name: "Eve",
last_name: "Holt",
avatar:
"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
},
{
id: 5,
first_name: "Charles",
last_name: "Morris",
avatar:
"https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
},
{
id: 6,
first_name: "Tracey",
last_name: "Ramos",
avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
}
]
};
我有JQuery Ajax请求从API:“ https://reqres.in/api/users?page=2”
获取数据答案 0 :(得分:0)
如果您使用的是Jquery :(客户端)
JSON.parse() Method:
var json_obj = '{"page":2,"per_page":3,"total":12,"total_pages":4,"data":[{"id":4,"first_name":"Eve","last_name":"Holt","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"},{"id":5,"first_name":"Charles","last_name":"Morris","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"},{"id":6,"first_name":"Tracey","last_name":"Ramos","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"}]}';
var obj = JSON.parse(json_obj);
更多示例:
答案 1 :(得分:0)
您需要遍历.data
数组。像这样:
let apiCall = 'https://reqres.in/api/users?page=2';
jQuery.getJSON(apiCall).then(function (res) {
let html = '';
res.data.forEach(user => {
html += `<tr>
<td><img src="${user.avatar}"></td><td>${user.first_name} ${user.last_name}</td>
</tr>`;
});
jQuery('#users').html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="users">
</table>