简体   繁体   English

如何使用JavaScript加载外部文件

[英]How to load external file using javascript

I use this code to change text by click on it, i need to load external file text.txt instead of insert it from same page. 我使用此代码通过单击来更改文本,我需要加载外部文件text.txt而不是从同一页面插入它。

 $(document).ready(function() { $("#div3").click(function() { changtext(); }); }); function changtext() { document.getElementById("div2").innerHTML = "thank you text has been changed"; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="div2">The text will get loaded here</div> <div id="div3">click me to chang text </div> 

what i need to change to load text.txt 我需要更改以加载text.txt

You can use the .load method. 您可以使用.load方法。 Also might want to change the title to how to load external file using Javascript with jquery. 也可能想将标题更改为如何使用带有jquery的Javascript加载外部文件。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div2">The text will get loaded here</div>
<div id="div3">click me to chang text </div>

<script type="text/javascript">
 $(document).ready(function() {
    $('#div3').click(function() {
    $('#div2').load('text.txt');
  });
});
</script>

text.txt should be in the same directory as the html file. text.txt应与html文件位于同一目录中。 Also, make sure there is text inside the file. 另外,请确保文件中包含文本。

JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html . JS可以读取本地文件(请参阅FileReader()),但不能自动读取:用户必须使用html将文件或文件列表传递给脚本。

You can refer: https://www.javascripture.com/FileReader to get more solution. 您可以参考: https : //www.javascripture.com/FileReader以获取更多解决方案。

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

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