简体   繁体   English

仅使用javascript读取TXT文件

[英]Reading TXT file only with javascript

It is possible to read line by line txt file from my HTML5 game resources? 可以从我的HTML5游戏资源中逐行读取txt文件吗? (Resources = one of folders in my game project) I keep in this file informations about levels in my game. (资源=我的游戏项目中的一个文件夹)我在这个文件中保留了关于游戏中关卡的信息。 I found only examples using PHP, Ajax, but all of this requires server, but I want to run my game on servers or offline mode. 我发现只使用PHP,Ajax的例子,但所有这些都需要服务器,但我想在服务器或离线模式下运行我的游戏。 Thanks in advance. 提前致谢。

One technique used often by templates and preprocessing languages (like LESS or CoffeeScript) is to use a script tag with a type attribute not recognized by browsers. 模板和预处理语言(如LESS或CoffeeScript)经常使用的一种技术是使用脚本标记,其type属性不被浏览器识别。 This causes it to be ignored by the browser and search engines, but be accessible by JavaScript. 这会导致浏览器和搜索引擎忽略它,但可以通过JavaScript访问。

demo | 演示 | code view 代码视图

  <script type="text/mygamelevel" id="level1">
    0010011001111011
    0011011100010
    10101110111101101
  </script>

  <script type="text/javascript">
    var level = document.getElementById("level1").text;
    var lines = level.split("\n");
    for (var i=0; i<lines.length; i++) {
      var line = lines[i];
      if (!line.trim()) continue;

      alert(line);
    }
  </script>

If a file is preferred, you can dynamically request it. 如果首选文件,您可以动态请求它。 This is an example using jQuery's get function. 这是使用jQuery的get函数的一个例子。

$.get('levels/level1.txt', function(level) {
    var lines = level.split("\n");
    for (var i=0; i<lines.length; i++) {
      var line = lines[i];
      if (!line.trim()) continue;

      alert(line);
    }
});

No guarantee is made that the code in the callback will be executed at any given time, so I suggest putting some start-new-level code in there, as opposed to anywhere else in the code. 不保证回调中的代码将在任何给定时间执行,因此我建议在其中放置一些启动新级代码,而不是代码中的任何其他位置。 Otherwise, you don't know if you have the level information downloaded yet or not. 否则,您不知道您是否已下载级别信息。 This problem is averted by inlining the data as shown in the first snippet of this answer. 通过内联数据来避免此问题,如本答案的第一个片段所示。

浏览器的JavaScript不会,也不应该直接访问本地文件系统。

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

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