简体   繁体   English

如何从文件中导入 JS 和 HTML?

[英]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在js文件中找到示例导入 请调整它以便将代码保存在js文件中 您好请帮助 在js文件中找到示例导入 请调整它以便将代码保存在js文件中

 <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文件 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.您可以使用XMLHttpRequest中的 XMLHttpRequest 向服务器请求数据。
file.open("GET", "b.js"); can be used to open the file.可用于打开文件。
file.responseText is used to get data from that file. file.responseText用于从该文件中获取数据。

Note:笔记:

Use this code on web server (local or online) to avoid CORS policy in some browsers. 在 web 服务器(本地或在线)上使用此代码,以避免某些浏览器中的 CORS 策略。
<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谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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