【问题标题】:How do I display the details in a JSON array in a html? [duplicate]如何在 html 中显示 JSON 数组中的详细信息? [复制]
【发布时间】:2019-06-27 07:53:57
【问题描述】:

我正在尝试将 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

【问题讨论】:

标签: javascript jquery html json ajax


【解决方案1】:

您需要遍历 .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>

【讨论】:

    【解决方案2】:

    如果您使用的是 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);
    

    更多示例:

    https://www.w3schools.com/js/js_json_parse.asp

    【讨论】:

      猜你喜欢
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 2016-07-05
      相关资源
      最近更新 更多