简体   繁体   中英

How can I import JS and HTML from a file?

Example import found in js file Please adjust it so that the code is saved in the js file Hello Please Help Example import found in js file Please adjust it so that the code is saved in the js file

 <html dir="rtl"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>table</title> </head> <script> function myim() { a.innerHTML = import code in b.js } </script> <body > <div id="a" align="center"> </div> <p> <input type="button" name="go" id="bn" value="import" onclick="myim()"></p> </body> </html>

file b.js

 <table border="1" cellpadding="0" style="border-collapse: collapse" width="80" dir="rtl"> <tr> <td>&nbsp;<span lang="en">number</span></td> </tr> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> <tr> <td>3</td> </tr> <tr> <td>4</td> </tr> <tr> <td>5</td> </tr> </table>

You can use XMLHttpRequest in javascript to request data from the server.
file.open("GET", "b.js"); can be used to open the file.
file.responseText is used to get data from that file.

Note:

Use this code on web server (local or online) to avoid CORS policy in some browsers.
<html dir="rtl">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>table</title>
</head>
<script>
  function myim() {
    var file = new XMLHttpRequest();
    file.open("GET", "b.js");
    file.onreadystatechange = function (){
        content = file.responseText;
        document.getElementById('a').innerHTML = content;
    }
    file.send(null);
  }
</script>

<body >
    <div id="a" align="center"></div>

    <p><input type="button" name="go" id="bn" value="import" onclick="myim()"></p>
</body>

</html>

Thank you

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