【问题标题】:Loading content dynamically from JSON file to HTML page through JS通过JS将内容从JSON文件动态加载到HTML页面
【发布时间】:2019-04-21 20:16:14
【问题描述】:

我正在尝试创建一个在线书店网站,因为我不必从数据库中获取数据,所以我考虑过从 JSON 文件加载我的图书对象。 我应该做的是:从 JSON 文件加载对象并动态构建页面(例如,一个页面包含所有可用书籍的列表,另一个页面带有带有过滤器的搜索栏等)。 我最近开始研究 HTML、CSS、JS(和 Node.JS),所以我不太确定自己能做什么,不能做什么。 我在网上读到我可以在我的 HTML 文件中使用 JQuery 从 URL 加载 JSON,但我仍然想知道:是否有机会在我的 JS 文件中加载 JSON 内容(可能通过 path 和 fs as在 Node.JS 中)并像动态内容一样使用它(例如通过 .innerHTML)?

【问题讨论】:

  • 简短的回答是是的Your question is too broad 给出更清晰的答案。考虑重新编写有关特定问题的问题,并包括一些代码和任何错误以及所需的结果。

标签: javascript html json


【解决方案1】:

您不需要服务器端代码。

假设您在与您的 javascript 文件相同的目录中有一个名为 books.json 的 JSON 文件:

{
  "books": [
    {"title": "book1", "author": "author1"},
    {"title": "book2", "author": "author2"}
  ]
}

还有一个index.html

<div id="books"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="script.js"></script>

在您的script.js 中,您可以使用 jQuery 像这样加载 JSON:

// global variable
var data;

$.get('books.json', function(d) {
  data = JSON.parse(d);
  // loop through all books
  data.books.forEach(function(b) {
    // now you can put every book in your <div>
    $("#books").append(`<div><h2>${b.title}</h2><p>${b.author}</p></div>`);
  });
});

搜索功能可以是这样的:

html:

<input id="input" /><button onclick="search()">search</button>

javascript:

function search() {
  $("#books").html("");
  let search = $("#input").val();
  // filter the data
  let filtered = $(data).filter(function (i,b){return b.title == search || b.author == search});
  filtered.books.forEach(function(b) {
    $("#books").append(`<div><h2>${b.title}</h2><p>${b.author}</p></div>`);
  });
}

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 2013-05-08
    • 2017-06-24
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多