基本上,我正在创建一个简单的宣传册网站,可以使用 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 吗?你通常是怎么做的?对于动态网站,我知道它通常存储在数据库中,但是对于静态网站来说呢?
1 回答

郎朗坤
TA贡献1921条经验 获得超9个赞
我会将它放在与 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
})
添加回答
举报
0/150
提交
取消