html JS.JSON。使用fetch API获取远程JSON数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html JS.JSON。使用fetch API获取远程JSON数据相关的知识,希望对你有一定的参考价值。

table {
  margin-top: 20px;
}
table, tr, td {
  border: 1px solid;
} 
function search() {
    var queryURL = "https://jsonplaceholder.typicode.com/users";

    fetch(queryURL)
            .then(function (response) {
                // response.json() returns a json string,
                // returning it will convert it 
                // to a pure JavaScript 
                // object for the next then's callback
                return response.json();
            })
            .then(function (users) {
                // users is a JavaScript object here
                displayUsersAsATable(users);
            })
            .catch(function (error) {
                console.log('Error during fetch: ' + error.message);
            });
}

function displayUsersAsATable(users) {
    // users is a JavaScript object

    // empty the div that contains the results
    var usersDiv = document.querySelector("#users");
    usersDiv.innerHTML = "";

    // creates and populate the table with users
    var table = document.createElement("table");

    // iterate on the array of users
    users.forEach(function (currentUser) {
        // creates a row
        var row = table.insertRow();
        // insert cells in the row
        var nameCell = row.insertCell();
        nameCell.innerHTML = currentUser.name;
        var cityCell = row.insertCell();
        cityCell.innerHTML = currentUser.address.city;
    });

    // adds the table to the div
    usersDiv.appendChild(table);
}
JS.JSON.Getting remote JSON data with the fetch API
---------------------------------------------------


A [Pen](https://codepen.io/Onlyforbopi/pen/EdYWgO) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).

[License](https://codepen.io/Onlyforbopi/pen/EdYWgO/license).
<!DOCTYPE html>
<html lang="en">
<head>
<title>Working with remote data</title>
  <meta charset="utf-8"/>
  <!-- Polyfill in case your browser does not support the fetch API -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/0.10.1/fetch.js"></script>

</head>
<body>
  <button onclick="search();">Get remote list of users' names and emails using the fetch API</button>
  <div id="users"></div>
</body>
</html>


以上是关于html JS.JSON。使用fetch API获取远程JSON数据的主要内容,如果未能解决你的问题,请参考以下文章

html JS.JSON.FetchingData.XHR.Fetch.ex1

动态 HTML 上的事件绑定,使用 fetch 和 forEach 内

使用 Fetch API 获取 json 格式的闪烁提要

获取向 Rails 服务器发出请求的 API

html JS.JSON。使用XhR2 API获取远程JSON数据

html JS.JSON。使用XhR2 API获取远程JSON数据