简体   繁体   English

如何导入.js 从 html 导入.json

[英]How to import .js that imported .json from html

I am not an English-speaking citizen, I am not good at English but I did best.我不是说英语的公民,我不擅长英语,但我做得最好。

I am trying to import a js file that imported json from html我正在尝试导入一个从 html 导入 json 的 js 文件

.js .js

import JSON from '../json/menu.json';

(function () {
  function parseMenu(ul, menu) {
    for (var i=0;i<menu.length;i++) {
      if(menu.sub == null) {
        menu.sort(function(a, b) {
          return a.id > b.id ? -1 : a.id > b.id ? 1 : 0;
        });
      }
      var li=$(ul).append('<li><a href="'+menu[i].link+'">'+menu[i].name+'</a></li>');
      if (menu[i].sub!=null) {
        var subul=$('<ul id="submenu'+menu[i].link+'"></ul>');
        $(li).append(subul);
        parseMenu($(subul), menu[i].sub);
      }
    }
  }
  var menu=$('#menu');
  parseMenu(menu, JSON);
});

.json form .json 表格

[ {
     {
     },
     {
     }
   },
   {
     {
     },
     {
     }
   },
   {
   }
]

I tried like我试过

<script type="module" src="../js/left.js"></script>
<script type="module" src="../json/menu.json"></script>

in html在 html

But I get the following error Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json".但是我收到以下错误加载模块脚本失败:需要 JavaScript 模块脚本,但服务器响应 MIME 类型为“application/json”。 Strict MIME type checking is enforced for module scripts per HTML spec.根据 HTML 规范,对模块脚本强制执行严格的 MIME 类型检查。 in.json in.json

I solved it.我解决了。

First.第一的。 Changed name of variable.更改了变量的名称。 JSON to menus JSON 到菜单

Second.第二。 Deleted <script type="module" src="../js/left.mjs"></script>已删除<script type="module" src="../js/left.mjs"></script>

Last.最后的。 Changed import JSON from '../json/menu.json'; import JSON from '../json/menu.json'; to import menus from '../json/menus.json' assert { type: "json" }; import menus from '../json/menus.json' assert { type: "json" };

My guess is you are actually trying to use the .js as src in this part:我的猜测是您实际上是在尝试将.js用作这部分中的 src:

<script type="module" src="../json/menu.json"></script>

Chrome currently supports https://github.com/tc39/proposal-import-assertions . Chrome 目前支持https://github.com/tc39/proposal-import-assertions This allows you to tell the browser that you are importing a json file:这允许您告诉浏览器您正在导入一个 json 文件:

import JSON from '../json/menu.json' assert { type: "json" };

By the way you shouldn't use JSON as the name of variable because it is a built-in object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON顺便说一句,您不应该使用JSON作为变量的名称,因为它是一个内置对象: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

This is working for me the way I wanted it to work;这按照我希望的方式为我工作; 解决方案

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

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