简体   繁体   中英

How do you save your post data on your blog even after reloading?

I'm trying to create a blog but it doesn't work. I want the blog to have it so it can save the posts in the blog so every time I reload it still has the same posts on the website (Off-topic question: How when you go onto for example stack overflow, it automatically creates a page for that question when you submit it?). But anyway, when I reload my website it resets the page and all the posts are lost! Currently, my code is this:

1: script.js, 2: blog.html

 function add_question() { let title = prompt('Enter a title'); let paragraph = prompt('Enter a paragraph'); let question_area = document.getElementById('question area'); let questionTag = document.createElement('span'); let titleTag = document.createElement('h2'); titleTag.innerText = title; let pTag = document.createElement('pre'); pTag.innerText = paragraph; [titleTag,pTag].forEach((tag) => {tag.style.textAlign = 'center'; questionTag.appendChild(tag)}) questionTag.style.border = '5px black solid'; questionTag.style.display = 'inline-block'; question_area.append(document.createElement('br'),document.createElement('br'),document.createElement('br')) question_area.appendChild(questionTag) }
 <!DOCTYPE html> <html> <head> <title>My Blog</title> <script src='script.js'></script> </head> <body> <h1 style='text-align: center;'>My Blog</h1> <button onclick=add_question()>New Post</button> <br><br><br> <div id='question area'> <div style='border: 7px black dashed;display:inline-block;align-self: center;'> <h2 style='text-align: center;'>Welcome!</h2> <pre style='text-align: center;'>This is where all my blog posts are!</pre> </div> </div> </body> </html>

So what do I need to do to fix this?

You could make use of the HTML5 local storage (accessed with .localStorage()) or the session storage, more on that here

You would maybe stringify the form data and do

localStorage.setItem("key", "value")

Alternatively, through javascript on the browser, you could save form data in a cookie, and read from it, though it would not be advised.

However, this is only to store form data. For your purposes (blog) you would need some server sided architecture to store, retrieve and process data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM