javascript 如何将文本文件包含到javascript中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7433250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:07:18  来源:igfitidea点击:

How to include text file into javascript

javascriptimportincludeinline

提问by mihai

Is there any way to load some text from another file into javascript, without server side code?

有没有办法将另一个文件中的一些文本加载到 javascript 中,而无需服务器端代码?

I was thinking to use another element to hold the text inside some comments, but I don't know how to read it's source code with javascript.

我想使用另一个元素来保存一些评论中的文本,但我不知道如何使用 javascript 阅读它的源代码。

Something like:

就像是:

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

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

<script> function readMyText() { ... }</script>

<script> function readMyText() { ... }</script>

In myfile.js: /* some text */

在 myfile.js 中: /* some text */

采纳答案by fmsf

Without using ajax or any server code... sorry mate but you can't :(

不使用 ajax 或任何服务器代码......对不起,伙计,但你不能:(

回答by Pointy

You can put anything you want into a script tag if you give it a "type" that's not something the browser understands as meaning "JavaScript":

如果你给它一个“类型”而不是浏览器理解为“JavaScript”的东西,你可以把任何你想要的东西放到脚本标签中:

<script id='Turtle' type='text/poem'>
  Turtle, turtle, on the ground;
  Pink and shiny - turn around.
</script>

You can get the contents via the "innerHTML" property:

您可以通过“innerHTML”属性获取内容:

var poemScript = document.getElementById('Turtle');
var poem = poemScript.innerHTML;

Here is a jsfiddle to demonstrate.

这是一个 jsfiddle 来演示。

That trick is popular lately with people doing client-side page building via templates.

这个技巧最近在人们通过模板进行客户端页面构建中很流行。

回答by Antonio Farmar

Building on Pointy's answer, to import from local files do this:

基于 Pointy 的回答,要从本地文件导入,请执行以下操作:

<script src="foo.txt" id="text" type="text">
</script>

You could also use this to target an external file:

您还可以使用它来定位外部文件:

<script src="http://foo.txt"></script>