使用Javascript读取服务器端文件

shi*_*juo 13 html javascript

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

var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
Run Code Online (Sandbox Code Playgroud)

Sei*_*idr 9

要实现此目的,您必须使用名为AJAX的方法从服务器检索文件.

我会研究一下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>
Run Code Online (Sandbox Code Playgroud)

如果将其上载到test.csv驻留在Web服务器上的目录并加载页面,则应该看到test.csv的内容出现在定义的textarea中.


jcu*_*bic 7

你需要使用AJAX.使用jQuery库,代码可以如下所示:

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

或者如果您不想使用库,请使用原始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);

更新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);
});
Run Code Online (Sandbox Code Playgroud)

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

  • 尝试提供更多有用的答案.我们喜欢看到比"去谷歌"更好的答案. (8认同)
  • 我拒绝了这个答案,但我已经达到了我的每日限制,所以把它作为警告:-) (2认同)