We just started 3. semester two weeks ago and are learning basic event/Dom/fetch manipulation.
I am supposed to fetch data from https://jsonplaceholder.typicode.com/users and get all names and phone numbers.
So here is what I did:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var userID = document.getElementById("userID");
const url1 = "https://jsonplaceholder.typicode.com/users/";
const url2 = "https://jsonplaceholder.typicode.com/users";
//JSON.stringify(data)
function getUser() {
fetch(url1 + userID.value)
.then(res => res.json())
.then(data => {
var all = "<p>" + "Name: " + data.name + "</p>";
all += "<p>" + "Phone: " + data.phone + "</p>";
document.getElementById("singleUser").innerHTML = all;
});
}
//***************Code that needs look on is right here ********************
function getAllUsers() {
fetch(url2)
.then(res => res.json())
.then(data => {
for (var i = 0; i < data.length; i++) {
console.log(data[i]);
var all = "<p>" + "Name: " + data[i].name + "</p>";
all += "<p>" + "Phone: " + data[i].phone + "</p>";
document.getElementById("allUsers").innerHTML = all;
}
//for (var key in data) {
// if(data.hasOwnProperty(key)) {
// document.getElementById("allUsers").innerHTML = data[key].name;
// }
//}
data.forEach(function(key) {
var users = "<p>" + "Name: " + key.name + "</p>";
users += "<p>" + "Phone: " + key.phone + "</p>";
document.getElementById("allUsers").innerHTML = users;
console.log(key.name);
});
});
}
<h1>Hello World!</h1>
<h1>Test if deployed on Tomcat via Travis Ci</h1>
<h6>Calculator Client</h6>
<input type="number" id="firstNumber"><br>
<input type="number" id="secondNumber"><br>
<div id="operations">
<button name="opr">+</button>
<button name="opr">-</button>
<button name="opr">X</button>
<button name="opr">/</button>
<br>
</div>
<button id="clear">Clear</button>
<p id="result"></p>
<h6>Dynamic UI manipulation with data obtained via fetch</h6>
<input type="number" id="userID">
<button onClick="getUser()">Get user</button>
<button onClick="getAllUsers()">Get all</button>
<br>
<div id="singleUser"></div>
<div id="allUsers"></div>
<script src="calculator.js" type="text/javascript"></script>
<script src="fetch.js" type="text/javascript"></script>
As you can see I managed to get the single users, which wasn't a problem, but trying to get multiple data rows seems to be a hassle to me. I tried 3 different ways all of them keep only giving me the last person in the array, though if I print it to the console it gives me all of it.
Please help me.