使用 Javascript 读取服务器端文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3567369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:14:07  来源:igfitidea点击:

Reading Server Side file with Javascript

javascripthtml

提问by shinjuo

Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?

有谁知道有关如何使用 JS 从服务器端文件读取数据的教程?当我谷歌它时,我似乎无法找到任何关于此的主题。我尝试使用但它似乎不起作用。我只想从文件中读取一些数据以显示在页面上。这甚至可能吗?

var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();

采纳答案by Seidr

To achieve this, you would have to retrieve the file from the server using a method called AJAX.

为此,您必须使用称为 AJAX 的方法从服务器检索文件。

I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.

我会研究 JavaScript 库,例如 Mootools 和 jQuery。它们使 AJAX 的使用非常简单。

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
        <script type="text/javascript">
            //This event is called when the DOM is fully loaded
            window.addEvent("domready",function(){
                //Creating a new AJAX request that will request 'test.csv' from the current directory
                var csvRequest = new Request({
                    url:"test.csv",
                    onSuccess:function(response){
                        //The response text is available in the 'response' variable
                        //Set the value of the textarea with the id 'csvResponse' to the response
                        $("csvResponse").value = response;
                    }
                }).send(); //Don't forget to send our request!
            });
        </script>
    </head>
    <body>
        <textarea rows="5" cols="25" id="csvResponse"></textarea>
    </body>
</html>

If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.

如果您将其上传到 test.csv 驻留在网络服务器上的目录并加载页面,您应该会看到 test.csv 的内容出现在定义的文本区域中。

回答by jcubic

You need to use AJAX. With jQuery library the code can look like this:

您需要使用 AJAX。使用 jQuery 库,代码如下所示:

$.ajax({ url: "test.csv", success: function(file_content) {
    console.log(file_content);
  }
});

or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers

或者,如果您不想使用库,请使用原始 XMLHTTPRequest 对象(但我在不同浏览器上有不同的名称

function xhr(){
  var xmlHttp;
  try{
    xmlHttp=new XMLHttpRequest(); 
  } catch(e) {
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
    } catch(e) {
      try {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      } catch(e) {
        alert("Your browser does not support AJAX!"); 
        return false;
      }
    }
  }
  return xmlHttp; 
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
  console.log(req.responseText);
};
req.send(null);

UPDATE 2017there is new fetch api, you can use it like this:

UPDATE 2017有新的 fetch api,你可以这样使用它:

fetch('test.csv').then(function(response) {
    if (response.status !== 200) {
        throw response.status;
    }
    return response.text();
}).then(function(file_content) {
    console.log(file_content);
}).catch(function(status) {
    console.log('Error ' + status);
});

the support is pretty goodif you need to support browser that don't support fetch API you can use polyfill that github created

如果您需要支持不支持 fetch API 的浏览器,则支持非常好,您可以使用github 创建的 polyfill