从服务器文件夹读取文本文件

时间:2018-08-09 06:42:04

标签: javascript reactjs

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

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

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()中插入不合理的路径,但仍然得到相同的输出

1 个答案:

答案 0 :(得分:-1)

您可以使用老式的XMLHttpRequest,但在我看来,只要您的浏览器位于list中,如今使用fetch会更加方便。

这里是使用方式:

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

请记住,JS IO是异步的,并且有多种方法可以返回异步结果:

  1. 回调
  2. 使用承诺

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

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

相关问题