Definition and Usage
The fetch()
method starts the process of fetching a resource from a server. The fetch()
method returns a Promise that resolves to a Response object.
Syntax
Parameters
|
Parameter | Description |
file | Optional. The name of a resource to fetch. |
Return Value
|
Type | Description |
Promise | A Promise that resolves to a Response object. |
loading some data from text file using , fetch() method
fetch('content/data.txt')
.then((response)=>{
return response.text();
})
.then((data)=>{
// return response.text();
// console.log(data);
document.write(data);
})
loading data from API..
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
fetch('https://jsonplaceholder.typicode.com/users')
.then((response)=>{
return response.json()
}).then((data)=>{
// document.write(data)
console.log(data)
})
</script>
</head>
<body>
</body>
</html>
loading data from API into document
<script>
fetch('https://jsonplaceholder.typicode.com/users')
.then((response)=>{
return response.json()
}).then((data)=>{
// document.write(data)
console.log(data)
for(var x in data){
document.write(`${data[x].name} - ${data[x].email} <br />`);
}
})
</script>