简体   繁体   中英

Reading TXT file only with javascript

It is possible to read line by line txt file from my HTML5 game resources? (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. 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. This causes it to be ignored by the browser and search engines, but be accessible by 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.

$.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不会,也不应该直接访问本地文件系统。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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