首页 > 解决方案 > 在 html 中存储动态内容数据的最佳实践是什么?

问题描述

基本上,我正在创建一个简单的宣传册网站,可以使用 Javascript 动态更改内容。每次单击该按钮时,它都会调用 .js 文件中的一个函数,该函数将其插入到 html 中。为此,我将这些数据放入 .js 文件中的变量中。问题是我发现数据太大并且 .js 文件混乱。

<button class="content-1">
<button class="content-2">

<div class="container">
  # change between content 1 and 2
</div>
// in my case there are more than 2 contents
// each content has other contents as well
// the question is where to put these data 

let contentOne = [ 
  "a lot of text data", 
  "a lot of text data",
  "a lot of text data"
]

# other code

现在我设法将它们分成另一个 .js 文件。但我只是想知道,是否有一种更清洁的方式来存储然后访问这些数据?喜欢使用 YAML 吗?你通常是怎么做的?

对于动态网站,我意识到它通常存储在数据库中,但是对于静态网站来说呢?

标签: javascripthtmljquery

解决方案


我会将它作为 JSON 放在不同的文件中。然后在您的 HTML 文件中,您有一个函数执行获取请求以从服务器获取 JSON 文件。

这确实意味着您在开发时需要一个网络服务器。您可以使用轻量级的http-server

然后,您的代码执行以下操作:

function hydrateData() {
  return fetch('data.json').then(response => response.json());
}

hydrateData().then(data => {

// the rest of your code that needs the data goes in here

})

推荐阅读