简体   繁体   中英

Include local html file in event (no server, no ajax)

The question boils down to this: how can I display a brand new main when someone press a button?

So a javascript code would look like this:

let post1 = document.getElementById('post1')
post1.onclick=function (){
  //bring in local file?
  //document.main.innerHTML=localHtmlFile
} 

And the HTML

<body>
    <button id="post1">Post 1</button>
    <main> </main>
</body>

I know similar stuff is done with Ajax. But this is not a request to a server, but just to a file in the same computer.

Any idea?


Edit

I'd just like some information for newbies like me:

Note: For security reasons, you can't fetch() files from your local filesystem (or run other such operations locally); to run the above example locally you'll have to run the example through a local webserver. MDN

This probably applies to XMLHttpRequests too.

(So as dumb as it seems we cant fetch our own files.)

I have added id to main tag, and stored a html string on localHtmlFile field.

try it

 window.localStorage.setItem('page', "<div>new content</div>"); let post1 = document.getElementById('post1') post1.onclick=function (){ //can I include something similar to this? document.getElementById('main').innerHTML=window.localStorage.readItem('page'); }
 <body> <button id="post1">Post 1</button> <main id="main"> </main> </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