簡體   English   中英

從另一個 JS 文件導入 json 對象

[英]Import json object from another JS file

我有文件 1,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

任何幫助將非常感激。

使用script標簽而不是import 刪除 js 文件中的export

  <script type="text/javascript" src="data.js"></script>

1.html

 <table id="table"> <tr> <th>ID</th> <th>Name</th> <th>Category</th> <th>Color</th> </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> 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>

數據.js

 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", }, ];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM