简体   繁体   中英

How to get saved data from html file?

I have some data saved inside the html file, which looks like this:

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

<body>

  <script type="text/javascript">
  document.__data = {
     id: 1,
     text: 'Test blob',
  };
  </script>
</body>

the data is saved locally inside the data.html file.
Now, I'm trying to load the data into a separate app.js file:

I initially tried accessing the document directly:

const getData = () => console.log(document.__data);

But that jsut returns as undefined so then I tried the following:

 // app.js
 const getData = async () => {
     const request = await fetch('./data.html');
     const data = await request.json();
     console.log(JSON.stringify(data));
 }

 getData();

But that just returns the following error:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Any idea how to go about this?

First off, adding custom, arbitrary properties to the document is not recommended, as in:

document.__data = { ... };

instead do something like eg

var data = { ... };

Now, assuming you want to access the inline data using an external app.js file, that file needs to be loaded after your inline one, or else it will come back undefined .

So this is how it needs to look like in your HTML:

<head>
</head>

<body>

  <script>
    var data = {
      id: 1,
      text: 'Test blob',
   };
  </script>

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

</body>

And your app.js

const getData = () => console.log(data);

getData();

If your external app.js loads within the head , as in your original HTML, you need to delay the getData() until the DOM is ready, and this is how it needs to look like in your app.js :

const getData = () => console.log(data);

window.addEventListener('DOMContentLoaded', (event) => {

    getData();

});

And the reason is simply that you can't access what comes later in the document as it is not loaded yet, hence the undefined issue in your first sample.


Below two snippets use inline script so you can see how it works. Just replace the getData() part with your app.js and it will work as well.

Showing it does work when DOMContentLoaded is finished.

 <head> <script> const getData = () => console.log(data); window.addEventListener('DOMContentLoaded', (event) => { getData(); }); </script> </head> <body> <script> var data = { id: 1, text: 'Test blob', }; </script> </body>

Showing it does not work when not delayed until DOM is finished

 <head> <script> const getData = () => console.log(data); getData(); </script> </head> <body> <script> var data = { id: 1, text: 'Test blob', }; </script> </body>

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