Hướng dẫn how to fetch data from api and display in html table - cách tìm nạp dữ liệu từ api và hiển thị trong bảng html

1

Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.
Learn more.

Trong mã của tôi, tôi muốn tìm nạp dữ liệu từ API và xem trong bảng HTML bằng JavaScript.

fetch["//dummy.restapiexample.com/api/v1/employees"].then[
  res => {
    res.json[].then[
      data => {
        console.log[data];
        if [data.length > 0] {

          var temp = "";
          data.forEach[[itemData] => {
            temp += "";
            temp += "" + itemData.id + "";
            temp += "" + itemData.employee_name + "";
            temp += "" + itemData.employee_salary + "";
          }];
          document.getElementById['data'].innerHTML = temp;
        }
      }
    ]
  }
]
ID Employee Name Salary

Dữ liệu API có thể xem nhưng khi tôi muốn xem các dữ liệu đó vào bảng HTML không hiển thị. Bất kỳ ý tưởng làm thế nào tôi hiển thị những dữ liệu được tìm nạp vào bảng HTML.

Hỏi ngày 21 tháng 10 năm 2020 lúc 7:03Oct 21, 2020 at 7:03

* RG JS Fetch Promise Json * | *** Geeks Get and Post using Fetch *** | Table Styling CSS | Restful Api JSON Array

Json Data Placeholder Users 10 | Fetch Api and Promises | MDN Promise

Web Workers Example

fetch[] allows you to make network requests similar to XMLHttpRequest [XHR]. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

Last Updated:

Tuesday December 21 2021 0714 AM

table {
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

td,
th {
  border: 2px solid #999;
  padding: 0.5rem;
}

// main.js...

// 1. GET request using fetch[]
fetch["//jsonplaceholder.typicode.com/users"]
  // Converting received data to JSON
  .then[[response] => response.json[]]
  .then[[json] => {
    
  // 2. Create a variable to store HTML table headers
    let li = `IDNameUser NameEmail PhoneWebsite`;

    // 3. Loop through each data and add a table row
    json.forEach[[user] => {
      li += `
        ${user.id}
				${user.name} 
        ${user.username}
				${user.email}
        ${user.phone}
        ${user.website}
			`;
    }];

    // 4. DOM Display result
    document.getElementById["users"].innerHTML = li;
  }];

// main.js

// 5. POST request using fetch[]
fetch["//jsonplaceholder.typicode.com/posts", {
  // 6. Adding method type
  method: "POST",

  // 7. Adding body or contents to send JSON Stringify
  body: JSON.stringify[{
    title: "foo",
    body: "bar",
    userId: 1
  }],

  // 8. Adding headers to the request
  headers: {
    "Content-type": "application/json; charset=UTF-8"
  }
}]
  // 9. Converting to JSON
  .then[[response] => response.json[]]

  // 10. Displaying results to console
  .then[[json] => console.log[json]];

CSS bên ngoài

Bút này không sử dụng bất kỳ tài nguyên CSS bên ngoài nào.

JavaScript bên ngoài

Bút này không sử dụng bất kỳ tài nguyên JavaScript bên ngoài nào.

Làm cách nào để hiển thị thông tin API trong HTML?

Cách hiển thị dữ liệu API trong HTML..
const p = tài liệu. getEuityByid ["mypelement"].
fetch['//example.com/movies.json'].
. sau đó [[phản hồi] => {.
Trả lời phản hồi. json [] ;.
. Sau đó [[dữ liệu] => {.
P. InnerText = Data ..

Làm cách nào để hiển thị dữ liệu JSON từ API trong HTML?

Sử dụng chức năng JSON.Stringify để hiển thị JSON được định dạng trong HTML.Nếu bạn có JSON không được định dạng, nó sẽ xuất ra nó theo một cách định dạng. stringify function to Display formatted JSON in HTML. If you have unformatted JSON It will output it in a formatted way.

Làm thế nào để bạn nhận được dữ liệu từ API bằng Fetch?

API tìm nạp cho phép bạn yêu cầu không đồng bộ cho tài nguyên.Sử dụng phương thức Fetch [] để trả về một lời hứa giải quyết thành một đối tượng phản hồi.Để có được dữ liệu thực tế, bạn gọi một trong các phương thức của đối tượng phản hồi, ví dụ: văn bản [] hoặc json [].Các phương pháp này giải quyết vào dữ liệu thực tế.call one of the methods of the Response object e.g., text[] or json[] . These methods resolve into the actual data.

Làm cách nào để hiển thị bảng JSON trong HTML?

Cách tiếp cận 1:..
Lấy đối tượng JSON trong một biến ..
Call a function which first adds the column names to the < table > element. [It is looking for the all columns, which is UNION of the column names]..
Traverse Dữ liệu JSON và Phù hợp với tên cột.....
Để trống cột nếu không có giá trị của khóa đó ..

Bài Viết Liên Quan

Chủ Đề