JS:
const button = document.querySelector('.js-button');
const output = document.querySelector('.js-output');
async function getRandomPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
const randomIndex = Math.floor(Math.random() * posts.length);
const randomPost = posts[randomIndex];
output.textContent = randomPost.body;
} catch (error) {
console.error('Error fetching data:', error);
}
}
document.addEventListener("DOMContentLoaded", async function() {
await getRandomPost();
});
button.addEventListener('click', async function() {
await getRandomPost();
});
html:
<button class="js-button">Get random post</button> <div class="js-output"></div>
Fetch params:
const fetchData = (url, userOptions = {}) => {
const defaultOptions = {
method: 'POST',
credentials: 'same-origin',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
'LoginToken': 'l0g1n-t0k3n'
}
};
// const options = jQuery.extend(defaultOptions, userOptions);
const options = Object.assign({}, defaultOptions, userOptions);
return fetch(url, options);
};
// Usage
fetchData(url)
.then(response => response.json())
.then(response => {
console.log(response);
})
.catch(error => console.error('Error: ', error));
fetchData(url, {method: 'GET'})
.then((response) => {
return response.text();
})
.then(response => {
let $responseContent = $(response).find('.content').html();
$('.content').html($responseContent);
})
.catch(error => console.error('Error: ', error));
All fetch() parameters:
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})