JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | const button = document.querySelector( '.js-button' ); const output = document.querySelector( '.js-output' ); async function getRandomPost() { try { 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:
1 2 3 | < button class = "js-button" >Get random post</ button > < div class = "js-output" ></ div > |
Fetch params:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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 }) |