如何将JSON fetch数据分离到不同的div中
How to separate JSON fetch data into different divs
我有 javascript 来获取 json 信息。我将在本地存储此 json 文件(我从 https://jsonplaceholder.typicode.com/users 下载了一个示例文件并为我的使用示例添加了生日对象)
我正在尝试将返回的 JSON 信息和 post 内容解析为 2 个单独的 div。我有一个名为“生日”的 json 对象。在我的脚本中,我有一个 var 集来调用名为“今天”的今天的日期。它在控制台中将日期打印为“05-12”,这也是我将“生日”格式化为 JSON 的方式。我不需要年份或时间。
我想要的是让脚本将“今天”与 json 对象“生日”进行比较。
如果今天 = 生日,那么我希望在今天的用户列表中显示该条目信息 div 以显示在页面的“今天生日”部分下。
如果今天不等于生日,我希望用户列表未来显示的所有其他条目 div 显示在页面的生日未来部分下。
什么都不应该post在两个领域都进行,只能在一个或另一个领域进行。
任何人都可以提供任何帮助,我们将不胜感激。我将在下面包含我的所有代码。该代码段可能会出错,因为我有 JSON 文件的本地路径而不是在线版本。
这是我的代码笔,代码笔没有生日 JSON 对象
https://codepen.io/abc-123-webguy/pen/poegaLq
JSON file:
<pre>
[
{
"id": 1,
"birthdate": "05-12",
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"birthdate": "05-12",
"name": "Leanne Graham",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"birthdate": "05-15",
"name": "Leanne Graham",
"username": "Samantha",
"email": "Nathan@yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
},
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
},
{
"id": 4,
"birthdate": "05-15",
"name": "Leanne Graham",
"username": "Karianne",
"email": "Julianne.OConner@kory.org",
"address": {
"street": "Hoeger Mall",
"suite": "Apt. 692",
"city": "South Elvis",
"zipcode": "53919-4257",
"geo": {
"lat": "29.4572",
"lng": "-164.2990"
}
},
"phone": "493-170-9623 x156",
"website": "kale.biz",
"company": {
"name": "Robel-Corkery",
"catchPhrase": "Multi-tiered zero tolerance productivity",
"bs": "transition cutting-edge web services"
}
},
{
"id": 5,
"birthdate": "05-16",
"name": "Leanne Graham",
"username": "Kamren",
"email": "Lucio_Hettinger@annie.ca",
"address": {
"street": "Skiles Walks",
"suite": "Suite 351",
"city": "Roscoeview",
"zipcode": "33263",
"geo": {
"lat": "-31.8129",
"lng": "62.5342"
}
},
"phone": "(254)954-1289",
"website": "demarco.info",
"company": {
"name": "Keebler LLC",
"catchPhrase": "User-centric fault-tolerant solution",
"bs": "revolutionize end-to-end systems"
}
},
{
"id": 6,
"birthdate": "05-18",
"name": "Leanne Graham",
"username": "Leopoldo_Corkery",
"email": "Karley_Dach@jasper.info",
"address": {
"street": "Norberto Crossing",
"suite": "Apt. 950",
"city": "South Christy",
"zipcode": "23505-1337",
"geo": {
"lat": "-71.4197",
"lng": "71.7478"
}
},
"phone": "1-477-935-8478 x6430",
"website": "ola.org",
"company": {
"name": "Considine-Lockman",
"catchPhrase": "Synchronised bottom-line interface",
"bs": "e-enable innovative applications"
}
},
{
"id": 7,
"birthdate": "05-19",
"name": "Leanne Graham",
"username": "Elwyn.Skiles",
"email": "Telly.Hoeger@billy.biz",
"address": {
"street": "Rex Trail",
"suite": "Suite 280",
"city": "Howemouth",
"zipcode": "58804-1099",
"geo": {
"lat": "24.8918",
"lng": "21.8984"
}
},
"phone": "210.067.6132",
"website": "elvis.io",
"company": {
"name": "Johns Group",
"catchPhrase": "Configurable multimedia task-force",
"bs": "generate enterprise e-tailers"
}
},
{
"id": 8,
"birthdate": "05-22",
"name": "Leanne Graham",
"username": "Maxime_Nienow",
"email": "Sherwood@rosamond.me",
"address": {
"street": "Ellsworth Summit",
"suite": "Suite 729",
"city": "Aliyaview",
"zipcode": "45169",
"geo": {
"lat": "-14.3990",
"lng": "-120.7677"
}
},
"phone": "586.493.6943 x140",
"website": "jacynthe.com",
"company": {
"name": "Abernathy Group",
"catchPhrase": "Implemented secondary concept",
"bs": "e-enable extensible e-tailers"
}
},
{
"id": 9,
"birthdate": "05-22",
"name": "Leanne Graham",
"username": "Delphine",
"email": "Chaim_McDermott@dana.io",
"address": {
"street": "Dayna Park",
"suite": "Suite 449",
"city": "Bartholomebury",
"zipcode": "76495-3109",
"geo": {
"lat": "24.6463",
"lng": "-168.8889"
}
},
"phone": "(775)976-6794 x41206",
"website": "conrad.com",
"company": {
"name": "Yost and Sons",
"catchPhrase": "Switchable contextually-based project",
"bs": "aggregate real-time technologies"
}
},
{
"id": 10,
"birthdate": "05-31",
"name": "Leanne Graham",
"username": "Moriah.Stanton",
"email": "Rey.Padberg@karina.biz",
"address": {
"street": "Kattie Turnpike",
"suite": "Suite 198",
"city": "Lebsackbury",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "ambrose.net",
"company": {
"name": "Hoeger LLC",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}
]
</pre>
JS 脚本
// Instantiates a new Request object with provided parameteres.
const users = new Request("examplejs.json", {
method: "GET",
"Content-Type": "application/json"
});
// Use the ES6 fetch method to handle the request.
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch(users)
.then(response => {
return response.json();
})
.then(data => {
// Loop over each user in the response and send it
// to the renderUser helper.
data.forEach(user => {
renderUser(user);
});
})
.catch(error => {
// If an error is found it will be caught here
// and can be subsequently handled.
console.log('Error Found:', error);
});
// Helper method which renders the user.
renderUser = (person) => {
// Creates a new element and assigns some class names to it.
let userContainer = document.createElement("div");
userContainer.className = "col-xs-12 col-sm-6 col-md-4";
// Configure the innerHTML and use the JSON object passed in from the
// request to formulate the data using ES6 template literals.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
if (dd<10)
{
dd='0'+dd;
}
if(mm<10)
{
mm='0'+mm;
}
today = mm+'-'+dd;
console.log(today);
userContainer.innerHTML = `
<div class="user">
<address>
<strong>${person.name}</strong><br>
${person.birthdate}<br>
${person.website}<br>
<a href="mailto:${person.email}">${person.email}</a>
</address>
</div>`;
// Find the ID 'user-list' and append the userContainer to it.
// This will cause it to display on the page.
document.getElementById("user-list-today").appendChild(userContainer);
document.getElementById("user-list-future").appendChild(userContainer);
}
body {
background-color: #efefef;
}
.user {
padding: 15px;
border: 1px solid #e9e9e9;
border-bottom-color: #d5d5d5;
border-bottom-width: 2px;
border-radius: 4px;
background-color: #fff;
color: #000;
margin: 5px;
}
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
background-color: #efefef;
}
.user {
padding: 15px;
border: 1px solid #e9e9e9;
border-bottom-color: #d5d5d5;
border-bottom-width: 2px;
border-radius: 4px;
background-color: #fff;
color: #000;
margin: 5px;
}
</style>
</head>
<script src="examplejs.js"></script>
<body>
<h1 style="text-align:center;">Birthday Today</h1>
<div class="container">
<div class="row">
<div id="user-list-today"></div>
</div>
</div>
<h1 style="text-align:center;">======================================================================================================</h1>
<h1 style="text-align:center;">Birthday Future</h1>
<div class="container">
<div class="row">
<div id="user-list-future"></div>
</div>
</div>
</body>
</html>
这是因为您将 相同 节点附加到两个不同的 div。如果您查看 appendChild
here 的文档,您可以看到:
The Node.appendChild() method adds a node to the end of the list of children of a
specified parent node. If the given child is a reference to an existing node in
the document, appendChild() moves it from its current position to the new
position (there is no requirement to remove the node from its parent node
before appending it to some other node).
因此,在您的 renderUser
函数中,您应该将今天的用户与未来的用户分开,并相应地附加每个用户。
举个例子,这里每个用户都被随机添加到任一列表;查看 renderUser
函数末尾附近的唯一变化:https://codepen.io/maeriens/pen/wvJMjqG
我有 javascript 来获取 json 信息。我将在本地存储此 json 文件(我从 https://jsonplaceholder.typicode.com/users 下载了一个示例文件并为我的使用示例添加了生日对象)
我正在尝试将返回的 JSON 信息和 post 内容解析为 2 个单独的 div。我有一个名为“生日”的 json 对象。在我的脚本中,我有一个 var 集来调用名为“今天”的今天的日期。它在控制台中将日期打印为“05-12”,这也是我将“生日”格式化为 JSON 的方式。我不需要年份或时间。
我想要的是让脚本将“今天”与 json 对象“生日”进行比较。 如果今天 = 生日,那么我希望在今天的用户列表中显示该条目信息 div 以显示在页面的“今天生日”部分下。
如果今天不等于生日,我希望用户列表未来显示的所有其他条目 div 显示在页面的生日未来部分下。
什么都不应该post在两个领域都进行,只能在一个或另一个领域进行。
任何人都可以提供任何帮助,我们将不胜感激。我将在下面包含我的所有代码。该代码段可能会出错,因为我有 JSON 文件的本地路径而不是在线版本。
这是我的代码笔,代码笔没有生日 JSON 对象 https://codepen.io/abc-123-webguy/pen/poegaLq
JSON file:
<pre>
[
{
"id": 1,
"birthdate": "05-12",
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"birthdate": "05-12",
"name": "Leanne Graham",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"birthdate": "05-15",
"name": "Leanne Graham",
"username": "Samantha",
"email": "Nathan@yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
},
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
},
{
"id": 4,
"birthdate": "05-15",
"name": "Leanne Graham",
"username": "Karianne",
"email": "Julianne.OConner@kory.org",
"address": {
"street": "Hoeger Mall",
"suite": "Apt. 692",
"city": "South Elvis",
"zipcode": "53919-4257",
"geo": {
"lat": "29.4572",
"lng": "-164.2990"
}
},
"phone": "493-170-9623 x156",
"website": "kale.biz",
"company": {
"name": "Robel-Corkery",
"catchPhrase": "Multi-tiered zero tolerance productivity",
"bs": "transition cutting-edge web services"
}
},
{
"id": 5,
"birthdate": "05-16",
"name": "Leanne Graham",
"username": "Kamren",
"email": "Lucio_Hettinger@annie.ca",
"address": {
"street": "Skiles Walks",
"suite": "Suite 351",
"city": "Roscoeview",
"zipcode": "33263",
"geo": {
"lat": "-31.8129",
"lng": "62.5342"
}
},
"phone": "(254)954-1289",
"website": "demarco.info",
"company": {
"name": "Keebler LLC",
"catchPhrase": "User-centric fault-tolerant solution",
"bs": "revolutionize end-to-end systems"
}
},
{
"id": 6,
"birthdate": "05-18",
"name": "Leanne Graham",
"username": "Leopoldo_Corkery",
"email": "Karley_Dach@jasper.info",
"address": {
"street": "Norberto Crossing",
"suite": "Apt. 950",
"city": "South Christy",
"zipcode": "23505-1337",
"geo": {
"lat": "-71.4197",
"lng": "71.7478"
}
},
"phone": "1-477-935-8478 x6430",
"website": "ola.org",
"company": {
"name": "Considine-Lockman",
"catchPhrase": "Synchronised bottom-line interface",
"bs": "e-enable innovative applications"
}
},
{
"id": 7,
"birthdate": "05-19",
"name": "Leanne Graham",
"username": "Elwyn.Skiles",
"email": "Telly.Hoeger@billy.biz",
"address": {
"street": "Rex Trail",
"suite": "Suite 280",
"city": "Howemouth",
"zipcode": "58804-1099",
"geo": {
"lat": "24.8918",
"lng": "21.8984"
}
},
"phone": "210.067.6132",
"website": "elvis.io",
"company": {
"name": "Johns Group",
"catchPhrase": "Configurable multimedia task-force",
"bs": "generate enterprise e-tailers"
}
},
{
"id": 8,
"birthdate": "05-22",
"name": "Leanne Graham",
"username": "Maxime_Nienow",
"email": "Sherwood@rosamond.me",
"address": {
"street": "Ellsworth Summit",
"suite": "Suite 729",
"city": "Aliyaview",
"zipcode": "45169",
"geo": {
"lat": "-14.3990",
"lng": "-120.7677"
}
},
"phone": "586.493.6943 x140",
"website": "jacynthe.com",
"company": {
"name": "Abernathy Group",
"catchPhrase": "Implemented secondary concept",
"bs": "e-enable extensible e-tailers"
}
},
{
"id": 9,
"birthdate": "05-22",
"name": "Leanne Graham",
"username": "Delphine",
"email": "Chaim_McDermott@dana.io",
"address": {
"street": "Dayna Park",
"suite": "Suite 449",
"city": "Bartholomebury",
"zipcode": "76495-3109",
"geo": {
"lat": "24.6463",
"lng": "-168.8889"
}
},
"phone": "(775)976-6794 x41206",
"website": "conrad.com",
"company": {
"name": "Yost and Sons",
"catchPhrase": "Switchable contextually-based project",
"bs": "aggregate real-time technologies"
}
},
{
"id": 10,
"birthdate": "05-31",
"name": "Leanne Graham",
"username": "Moriah.Stanton",
"email": "Rey.Padberg@karina.biz",
"address": {
"street": "Kattie Turnpike",
"suite": "Suite 198",
"city": "Lebsackbury",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "ambrose.net",
"company": {
"name": "Hoeger LLC",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}
]
</pre>
JS 脚本
// Instantiates a new Request object with provided parameteres.
const users = new Request("examplejs.json", {
method: "GET",
"Content-Type": "application/json"
});
// Use the ES6 fetch method to handle the request.
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch(users)
.then(response => {
return response.json();
})
.then(data => {
// Loop over each user in the response and send it
// to the renderUser helper.
data.forEach(user => {
renderUser(user);
});
})
.catch(error => {
// If an error is found it will be caught here
// and can be subsequently handled.
console.log('Error Found:', error);
});
// Helper method which renders the user.
renderUser = (person) => {
// Creates a new element and assigns some class names to it.
let userContainer = document.createElement("div");
userContainer.className = "col-xs-12 col-sm-6 col-md-4";
// Configure the innerHTML and use the JSON object passed in from the
// request to formulate the data using ES6 template literals.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
if (dd<10)
{
dd='0'+dd;
}
if(mm<10)
{
mm='0'+mm;
}
today = mm+'-'+dd;
console.log(today);
userContainer.innerHTML = `
<div class="user">
<address>
<strong>${person.name}</strong><br>
${person.birthdate}<br>
${person.website}<br>
<a href="mailto:${person.email}">${person.email}</a>
</address>
</div>`;
// Find the ID 'user-list' and append the userContainer to it.
// This will cause it to display on the page.
document.getElementById("user-list-today").appendChild(userContainer);
document.getElementById("user-list-future").appendChild(userContainer);
}
body {
background-color: #efefef;
}
.user {
padding: 15px;
border: 1px solid #e9e9e9;
border-bottom-color: #d5d5d5;
border-bottom-width: 2px;
border-radius: 4px;
background-color: #fff;
color: #000;
margin: 5px;
}
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
background-color: #efefef;
}
.user {
padding: 15px;
border: 1px solid #e9e9e9;
border-bottom-color: #d5d5d5;
border-bottom-width: 2px;
border-radius: 4px;
background-color: #fff;
color: #000;
margin: 5px;
}
</style>
</head>
<script src="examplejs.js"></script>
<body>
<h1 style="text-align:center;">Birthday Today</h1>
<div class="container">
<div class="row">
<div id="user-list-today"></div>
</div>
</div>
<h1 style="text-align:center;">======================================================================================================</h1>
<h1 style="text-align:center;">Birthday Future</h1>
<div class="container">
<div class="row">
<div id="user-list-future"></div>
</div>
</div>
</body>
</html>
这是因为您将 相同 节点附加到两个不同的 div。如果您查看 appendChild
here 的文档,您可以看到:
The Node.appendChild() method adds a node to the end of the list of children of a
specified parent node. If the given child is a reference to an existing node in
the document, appendChild() moves it from its current position to the new
position (there is no requirement to remove the node from its parent node
before appending it to some other node).
因此,在您的 renderUser
函数中,您应该将今天的用户与未来的用户分开,并相应地附加每个用户。
举个例子,这里每个用户都被随机添加到任一列表;查看 renderUser
函数末尾附近的唯一变化:https://codepen.io/maeriens/pen/wvJMjqG