代码之家  ›  专栏  ›  技术社区  ›  shinjuo

用Javascript读取服务器端文件

  •  13
  • shinjuo  · 技术社区  · 14 年前

    有人知道如何用JS从服务器端文件读取数据的教程吗?我在谷歌上找不到任何关于这个的话题。我试过用,但似乎不起作用。我只想从文件中读取一些数据以显示在页面上。这有可能吗?

    var CSVfile = new File("test.csv");
    var result = CVSfile.open("r");
    var test = result.readln();
    
    2 回复  |  直到 14 年前
        1
  •  9
  •   GOXR3PLUS    7 年前

    <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>
    

    如果你把它上传到测试.csv驻留在您的Web服务器上并加载页面时,您应该可以看到测试.csv出现在定义的文本区域中。

        2
  •  7
  •   jcubic    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);
    });
    

    the support is pretty good 如果需要支持不支持fetchapi的浏览器,可以使用polyfill github created