简体   繁体   English

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

[英]How to include text file into javascript

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> function readMyText() { ... }</script>

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

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. 这个技巧最近流行,人们通过模板进行客户端页面构建。

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

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>

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

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