【问题标题】:Reading text file from server folder从服务器文件夹中读取文本文件
【发布时间】:2018-08-09 06:42:03
【问题描述】:

我正在尝试从保存网站的文件夹中读取文本文件。

文件与我尝试从中读取文件的类位于同一文件夹中。

config.json(我正在尝试读取的文件)包含:

{
"DATE": "Datum"
}

我的代码:

function loadFile(filePath) {
    var result = null;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", filePath, false);
    xmlhttp.send();
    if (xmlhttp.status==200) {
      result = xmlhttp.responseText;
    }
    return result;
  }


  var myStuff = loadFile("config.json");
    console.log(myStuff);

输出

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dispečink</title>
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,500,700' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  </head>
  <body>
    <div id="root"></div>
  <script type="text/javascript" src="/static/js/bundle.js"></script></body>
</html>

我的问题是我得到了我没想到的输出。

如何从 config.json 中获取正确的数据?

我尝试向 loadFile() 插入无意义的路径,但仍然得到相同的输出

【问题讨论】:

  • xmlhttp.open("GET", filePath, false); — 不推荐使用同步请求。不要那样做。
  • 您未能包含明确的问题陈述。您刚刚提供了一些代码,但没有说明问题所在。
  • 我尝试向 loadFile() 插入无意义的路径,但仍然得到相同的输出 — 那是什么输出?
  • @Quentin 我正在尝试从 config.json 加载数据...输出是 output。在输出中不是 config.json 中的数据
  • HTML 是响应?那么问题是你的网址是错误的。您尝试加载的数据可能没有 URL。您需要找到正确的 URL 或创建一个可以为您提供数据的 URL。问题与客户端代码无关。

标签: javascript reactjs


【解决方案1】:

你可以使用老派的XMLHttpRequest,但我认为现在使用fetch要方便得多,前提是你的浏览器在这个list中。

这里是你如何使用它:

function loadFile(filePath) {
  return fetch("/file.json").then(response => response.json())
}

记住,JS IO 是异步的,返回异步结果有多种方式:

  1. 回调
  2. 使用承诺

fetch 使用承诺。我强烈建议熟悉它们。

希望我的回答对你有帮助!祝你好运。

【讨论】:

  • “记住 JS IO 是异步的”——问题中的代码不是。
猜你喜欢
  • 2014-01-18
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
相关资源
最近更新 更多