Reading Server Side file with Javascript

前端 未结 2 1550
轮回少年
轮回少年 2020-12-15 23:32

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 s

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 00:09

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

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

    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 2017 there is new fetch api, you can use it like this:

    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 if you need to support browser that don't support fetch API you can use polyfill that github created

提交回复
热议问题