显示从api到html表的信息

时间:2018-12-05 12:16:17

标签: javascript ajax

我在使用api时遇到问题,我尝试过console.log(response.[""0""].body)在控制台上获得了响应,但它不起作用。我需要从表中的api中获取所有这些数据。

这是我的代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
   Js code

    var root = 'https://jsonplaceholder.typicode.com';
    $.ajax({
     url: root + '/posts',
     method: 'GET',
     success: function(response) {
     console.log(response);
     }
     
    });
    var body = document.getElementsByTagName('body')[0];
    var table = document.createElement('table');
    body.appendChild(table);
    table.setAttribute('id', 'mytable');
    var createrow = function(c1,c2){
        var row = document.createElement('tr');
        row.appendChild(c1);
        row.setAttribute('class', 'row')
        row.appendChild(c2); 
    
        return row;
    }
    var createcell = function(value){
        var cell = document.createElement('td');
        cell.setAttribute('class', 'cell');
        cell.innerText=value;
        return cell;
    }
    
    
    table.appendChild(createrow(createcell('Mihaela'),createcell('11')))
</script>

2 个答案:

答案 0 :(得分:0)

尝试使用console.log(响应[0] .body)

答案 1 :(得分:0)

我已经为您提供了一个示例,其中使用了新的Fetch API,该示例使用零依赖的原始JavaScript编写。

const root = 'https://jsonplaceholder.typicode.com';

const asyncFetchPosts = async() => (
  fetch(`${root}/posts`)
  .then(res => res.json())
);


const start = async() => {
  const posts = await asyncFetchPosts();
  const tableHead = document.getElementById('myTableHead');
  const tableBody = document.getElementById('myTableBody');
  
  // Let's read all property keys from the first post
  // Array: [userId, id,	title,	body]
  const keys = Object.keys(posts[0]);

  // Add table head row
  const tableHeadRow = tableHead.insertRow(tableHead.rows.length);

  // Iteare over keys to create the header
  keys.forEach((key, i) => {    
    const newCell = tableHeadRow.insertCell(i);
    const newText = document.createTextNode(key);
    newCell.appendChild(newText);
  });
  
  // Iteare over all posts
  posts.forEach(post => {
    const newRow = tableBody.insertRow(tableBody.rows.length);
    
    // Now iterate over the keys for each post
    keys.forEach((key, i) => {
      const newCell = newRow.insertCell(i);
      const newText = document.createTextNode(post[key]);
      newCell.appendChild(newText);
    })
  });
}

// Call start
start();
<table id="myTable" border="1">
  <thead id="myTableHead">
  </thead>
  <tbody id="myTableBody">
  </tbody>
</table>