如何在JavaScript中加载文本文件? [英] How to load a text file in JavaScript?

查看:98
本文介绍了如何在JavaScript中加载文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的WebGL项目,需要一种方法来加载模型。我决定使用OBJ格式,所以我需要一种方法来加载它。文件(将要)存储在服务器上,我的问题是:JS中的一个如何加载文本文件并逐行扫描,令牌(如C ++中的流)?我是JS的新手,因此我的问题。更简单的方法,更好。

I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.

更新:我使用了你的解决方案,broofa,但我不确定我是否做得对。我从你编写的forEach循环中的文件中加载数据,但在它之外(即在你的所有代码之后),我填充数据的对象是未定义。我究竟做错了什么?这是代码:

UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:

var materialFilename;

function loadOBJModel(filename)
{
    // ...

    var req = new XMLHttpRequest();
    req.open('GET', filename);
    req.responseType = 'text';
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            var lines = req.responseText.split(/\n/g);
            lines.forEach(function(line)
            {
                readLine(line);
            });
        }
    }
    req.send();

    alert(materialFilename);

    // ...
}

function readLine(line)
{
    // ...

    else if (tokens[0] == "mtllib")
    {
        materialFilename = tokens[1];
    }

    // ...
}


推荐答案

您可以使用 XMLHttpRequest 获取文件,假设它来自与主网页相同的域。如果没有,并且您可以控制托管文件的服务器,则可以启用 CORS 没有太多麻烦。例如,

You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.

要逐行扫描,可以使用split()。例如。像这样...

To scan line-by-line, you can use split(). E.g. Something like this ...

var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
  if (req.readyState == 4) {
    if (req.status == 200) {
      var lines = req.responseText.split(/\n/g);
      lines.forEach(function(line, i) {
        // 'line' is a line of your file, 'i' is the line number (starting at 0)
      });
    } else {
      // (something went wrong with the request)
    }
  }
}

req.send();

这篇关于如何在JavaScript中加载文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆