简体   繁体   English

即使在重新加载后,您如何将帖子数据保存在博客上?

[英]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 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您可以使用 HTML5 本地存储(通过 .localStorage() 访问)或会话存储,更多关于这里

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.或者,通过浏览器上的 javascript,您可以将表单数据保存在 cookie 中,并从中读取,尽管不建议这样做。

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.出于您的目的(博客),您需要一些服务器端架构来存储、检索和处理数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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