I am developing a page that use a ajax request to read a JSON file and I am displaying it by looping on clicks but when I refresh page it returns to first screen is there anyway to return the same screen after I refresh please no JQUERY
CodePudding user response:
Here I have made a "framework" for maintaining the stat of your page.
The AJAX request happens when the hash in the URL changes (here the state is "state1": http://example.org/#state1
). There is an event listener for the hashchange
event and a function fetshdata()
.
When clicking the button "Get Data", the hash will change, the hashchange
event will happen and the function fetshdata()
will be called.
If the page is reloaded (this is your problem) the "state" of the page is maintained in the hash (the hash is still in the URL). To tricker the hashchange
event I made the hashchange event "by hand" and dispatch it on the window.
The state of the page could also be maintained in localStorage, but the advantage with the hash in the URL is that the hash change becomes part of the history in the browser and you can save/send/link to the URL etc.
const data = 'data:application/json;base64,W3sidGl0bGUiOiJJdGVtIDEifSx7InRpdGxlIjoiSXRlbSAyIn0seyJ0aXRsZSI6Ikl0ZW0gMyJ9XQ==';
var content;
const fetchdata = hash => {
let url = hash; //use the hash as part of the AJAX request (not implemented)
fetch(data).then(res => res.json()).then(json => {
content.innerHTML = '';
json.forEach(item => {
content.innerHTML = `<p>${item.title}</p>`;
});
});
};
document.addEventListener('DOMContentLoaded', e => {
content = document.getElementById('content');
document.getElementById('btn_load').addEventListener('click', e => {
location.hash = 'newstate';
});
document.getElementById('btn_reload').addEventListener('click', e => {
location.reload();
});
if(location.hash){
let event = new Event('hashchange');
window.dispatchEvent(event);
}
});
window.addEventListener('hashchange', e => {
let hash = location.hash.substring(1);
fetchdata(hash);
});
<button id="btn_load">Get data</button>
<button id="btn_reload">Reload</button>
<div id="content"></div>