简体   繁体   English

Javascript-如何下载JSON / AJAX文件并离线访问

[英]Javascript - How to download JSON/AJAX files and access it offline

As the title says. 如标题所示。 I have the following code below for javascript which fetch a file from webserver. 我下面的javascript代码从网络服务器获取文件。 My problem is that i want the user to access/load the JSON inside <script> tag and make it available for offline use? 我的问题是我希望用户访问/加载<script>标记内的JSON并使其可脱机使用吗? Eg if the user is does not internet the <script> would still fetch the files. 例如,如果用户不上网, <script>仍将获取文件。 Is there any way to achieve it? 有什么办法可以实现?

<!DOCTYPE html>
<html>
<body>

<h2>Convert a JavaScript object into a JSON string, and send it to the server.</h2>

<script>
var myObj = { name: "John", age: 31, city: "New York" };
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
</script>

</body>
</html>

You can save the data into localStorage or indexDB, this will work fine if the user is using a newer browser. 您可以将数据保存到localStorage或indexDB中,如果用户使用的是更新的浏览器,则可以正常工作。

Another thing you can do is create a service worker that will cache the data. 您可以做的另一件事是创建将缓存数据的服务工作者。

You can check out Google's documentation for service workers for offline apps here: https://developers.google.com/web/fundamentals/codelabs/offline/ 您可以在这里查看Google为离线应用程序的服务人员提供的文档: https//developers.google.com/web/fundamentals/codelabs/offline/

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

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