猿问

从另一个 JS 文件导入 json 对象

我有 file1,data.js:


export var data = [

    {

        id : "001",

        name : "apple",

        category : "fruit",

        color : "red"

    },

    {

        id : "002",

        name : "melon",

        category : "fruit",

        color : "green"

    },

    {

        id : "003",

        name : "banana",

        category : "fruit",

        color : "yellow"

    }

]


module.exports = data;

我有 file2,index.html:


<table id="table">

    <tr>

        <th>ID</th>

        <th>Name</th>

        <th>Category</th>

        <th>Color</th>

    </tr>

</table>



<script src="jquery.js"></script>

<script>

import {data} from 'data.js';


for(var i = 0; i < data.length; i++) {

    var row = '<tr><td>' + data[i].id + '</td>';

    row+= '<td>' + data[i].name+ '</td>';

    row+= '<td>' + data[i].category + '</td>';

    row+= '<td>' + data[i].color + '</td></tr>';

    $("#table").append(row);

}

</script>

问题出在这一行:


import {data} from 'data.js';

如果我将数据变量直接包含在index.html中,它工作正常,但是当我尝试从它自己的单独文件引用它时,它不起作用。


它抛出的错误是:


  Unexpected token { import call expects exactly one argument

任何帮助将非常感激。


HUH函数
浏览 117回答 1
1回答

慕斯709654

使用script标签代替import. export在js文件中删除。&nbsp; <script type="text/javascript" src="data.js"></script>1.html<table id="table">&nbsp; <tr>&nbsp; &nbsp; <th>ID</th>&nbsp; &nbsp; <th>Name</th>&nbsp; &nbsp; <th>Category</th>&nbsp; &nbsp; <th>Color</th>&nbsp; </tr></table><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script type="text/javascript" src="data.js"></script><script>&nbsp; for (var i = 0; i < data.length; i++) {&nbsp; &nbsp; var row = "<tr><td>" + data[i].id + "</td>";&nbsp; &nbsp; row += "<td>" + data[i].name + "</td>";&nbsp; &nbsp; row += "<td>" + data[i].category + "</td>";&nbsp; &nbsp; row += "<td>" + data[i].color + "</td></tr>";&nbsp; &nbsp; $("#table").append(row);&nbsp; }</script>数据.jsvar data = [&nbsp; {&nbsp; &nbsp; id: "001",&nbsp; &nbsp; name: "apple",&nbsp; &nbsp; category: "fruit",&nbsp; &nbsp; color: "red",&nbsp; },&nbsp; {&nbsp; &nbsp; id: "002",&nbsp; &nbsp; name: "melon",&nbsp; &nbsp; category: "fruit",&nbsp; &nbsp; color: "green",&nbsp; },&nbsp; {&nbsp; &nbsp; id: "003",&nbsp; &nbsp; name: "banana",&nbsp; &nbsp; category: "fruit",&nbsp; &nbsp; color: "yellow",&nbsp; },];
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答