简体   繁体   中英

When importing a .json file into javascript my HTML file loses the ability to call functions from the javascript code

Hey this is really bizarre.

I will give some code examples here:

HTML:

<body style="background-color:rgb(157, 163, 163)" onload="createData()">
    <script src="indexLIS.js"></script>
    <script src="assets/initData.json"></script>
</body>

Javascript:

//import dataSource from './assets/initData.json';
function createData(){
    console.log("hey");
}

JSON:

{
    "dataSource":[
        {
            "id": 0,
            "name":"TemporaryName",
            "node-level":0
         }
     ]
}

In a code example even this simple, each time I open the HTML I get "hey" printed to the console almost immediately. However, if I uncomment the first line of the javascript code there and import the data from initData.json, then I immediately get the error "createData not defined" as though the HTML code has completely lost the ability to communicate with the javascript file.

EDIT : I just realized you were using es6 module syntax above (it read like a code comment to me). You might want to check out this question: How to import a json file in ecmascript 6?

Original answer :


You can't load json in a script tag. When you do, the browser is unable to parse it, and that kills all script execution on the page.

If you change your initData.json file to initData.js :

var jsonData = {
    "dataSource":[
        {
            "id": 0,
            "name":"TemporaryName",
            "node-level":0
         }
     ]
};

You should then be able to reference the data from the global jsonData variable.

I was eventually able to get it working for me. I can't say for sure if this will be the answer that works best for everyone but it accomplished what I set out to do.

HTML:

<body style="background-color:rgb(157, 163, 163)" onload="createData()">
    <script type="text/javascript" src="indexLIS.js"></script>
</body>

Javascript:

function createData() {
    $.getJSON('./assets/initData.json', function(json) {
        console.log(json.dataSource);
    });
}

Nothing changed in the Json itself, so I wont post that, but this way I was able to import the JSON data and interact with it without killing the relationship between the javascript file and the html. It might seem limiting to have to do everything you want to do with the json inside of the function(json){} section, but all I do in there is just send json out to another function, so it really doesn't slow me down at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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