首页 > 解决方案 > 获取文件到全局变量 Javascript

问题描述

有没有更好的方法来获取 .txt 文件,而不必将其写入隐藏段落然后从中读取?我想在全局变量中获取 .txt 文件的内容。

这就是我现在得到的:

async function loadFileAndPrintToConsole(url) {
  try {
    const response = await fetch(url);
    const data = await response.text();
    //console.log(data);
    document.getElementById("debug1").innerHTML = data;
  } catch (err) {
    console.error(err);
    setTestVariable(err);
  }
  getAlert();
}

function getVariable(){
  txtVariable = document. getElementById("debug1").innerHTML;
}

这可以更简单地实现吗?

标签: javascriptfetch

解决方案


而不是 document.getElementById("debug1").innerHTML = data; 你可以写 window.debug1 = data. 这就是我们设置全局变量的方式。

谢谢@pooria


推荐阅读