js 读取本地文件内容(txt等)

var xmlhttp;

function loadData(url, cfunc) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = cfunc;
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
};

function readFile(url) {
  loadData(url, function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      console.log('读取的数据 ==== ', xmlhttp.responseText);
      return xmlhttp.responseText;
    } else {
      return '';
    }
  })
};

注意如果在 vue 项目中使用,需要将文件放到 public 文件夹中,读取时直接使用文件名称即可,如:readFile('/***.txt'),确保路径为 localhost:8080/****.txt

猜你喜欢

转载自blog.csdn.net/strong90/article/details/102817890