简体   繁体   English

将本地 JSON 文件加载到 HTML 模板中

[英]Load local JSON File into a HTML template

I'm trying to load a json file into to an html template, so I can view the content in a formated way inside my browser.我正在尝试将 json 文件加载到 html 模板中,以便我可以在浏览器中以格式化的方式查看内容。 The json file is generated by a Java project. json 文件由 Java 项目生成。 I already tried to do this with javascript but it seems to be that java only can fetch a json file from a server and not from a local directory.我已经尝试用 javascript 来做到这一点,但似乎 java 只能从服务器而不是从本地目录获取 json 文件。 Is their any way to do this with javascript or typescript or maybe something else?他们有什么办法可以用javascript或打字稿或其他东西来做到这一点吗?

You can use fetch API to retrieve the informations of your JSON and if you use VSCode you can just launch the plugin Live Server to test it in your local directory.您可以使用fetch API 来检索您的 JSON 信息,如果您使用 VSCode,您只需启动插件 Live Server 即可在您的本地目录中对其进行测试。

  fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Live Server Plugin for VSCode https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer VSCode 的实时服务器插件https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

You can use fetch to retrieve it from a remote server or have a <input type="file" ... /> and let the user pick the JSON file using the "Open File" file browser dialog.您可以使用fetch从远程服务器检索它,或者使用<input type="file" ... />并让用户使用“打开文件”文件浏览器对话框选择 JSON 文件。

You can also include the JSON file from disk at compile-time when compile the application using TypeScript.当使用 TypeScript 编译应用程序时,您还可以在编译时从磁盘包含 JSON 文件。

There are also the File API , FileReader API , and FileSystem API to manage files locally on disk at runtime.还有File APIFileReader APIFileSystem API用于在运行时本地管理磁盘上的文件。 But these might only be able to read files written by the web browser that reside in certain locations and might not be able to access any file on file system due to security and sandboxing.但是这些可能只能读取由 Web 浏览器写入的位于某些位置的文件,并且由于安全性和沙箱的原因可能无法访问文件系统上的任何文件。

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

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