在没有服务器的情况下加载JSON文件 [英] Load a JSON file without server

查看:110
本文介绍了在没有服务器的情况下加载JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的json文件(+ -10mb).我想在位于HTML网页中的Javascript函数中将此json文件(myjson.json)加载.我在Google上找到了很多答案,说重命名为myjson.js"之类的内容并添加var data = " yourjson",并且在您的html文件中包括myjson.js并访问了变量数据.这不是我想要的.我想在不重命名/更改文件且没有网络服务器的情况下加载JSON文件(无AJAX).

I have a big json file (+-10mb). I want to load in this json file (myjson.json) in a Javascript function located in a HTML webpage. I found a lot of answers on google that say things like "rename to myjson.js" and add var data = " yourjson" and in your html file include myjson.js and acces the variable data. This is not what I want. I want to load in the JSON file without renaming/altering it and without a webserver (No AJAX).

有人可以帮助我吗?

  $.getJSON('myjson.json', function(myjson) {...}

将无法正常工作.

包含css和js函数非常容易,为什么没有网络服务器就无法访问本地存储的json文件?

Including css and js functions is so easy why is it so impossible to access a locally stored json file without a webserver?

json文件的第一行

[{"participants": ["a", "b"], "conversation": [{"sender": "b", "created_at": "2019-09-23T22:04:42.083698+00:00", "text": "xxx"},

添加我的js进行澄清

不能,因为我在移动设备上并且代码格式在这里不起作用

推荐答案

不幸的是,XHR和Fetch API都与HTTP有着千丝万缕的联系,除非涉及HTTP服务器,否则无法将其用于从相对路径加载资源.如果通过file: URL加载页面,则将无法使用XHR或Fetch获取该数据.

Unfortunately, both XHR and the Fetch API are inextricably tied to HTTP, and cannot be used to load a resource from a relative path unless an HTTP server is involved. If you're loading your page via a file: URL, you won't be able to use XHR or Fetch to get that data.

只有两种方法可供您使用:

There are only two methods available to you:

  • 切换到JavaScript而不是常规JSON,并使用<script>标记(如先前在其他答案中向您建议的那样)

  • Switch to JavaScript instead of regular JSON and use a <script> tag (as previously suggested to you in another answer)

允许用户拖放JSON文件(或使用<input type="file">)以获取文件引用,然后可以加载该文件引用.

Allow the user to drag/drop the JSON file (or use <input type="file">) to get a File reference that you can then load.

这篇关于在没有服务器的情况下加载JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆