【问题标题】:jQuery to read file content to variable inside JavaScript [duplicate]jQuery将文件内容读取到JavaScript中的变量[重复]
【发布时间】:2017-05-30 23:31:44
【问题描述】:

我已经为我的特殊困境寻找答案,我认为这一定与我自己的误解有关(我是 JS 新手)。我知道类似的主题,但没有完全解决我想确定的内容 - 如果我错过了之前发布的内容,请原谅我。

我已经总结了我正在尝试对以下 JavaScript 执行的操作,该 JavaScript 利用 jQuery 的 get 将文件内容读取到变量(我试图避免使用 XMLHttpRequest() 来读取文件所涉及的所有喧嚣)服务器端):

window.onload = function(){

var refFile = "./myFile"; // path to my txt file
var fileContent;

    $.get(refFile, function(response) {
         fileContent = response;
         alert(fileContent);  // I get data here just fine
    });

    alert(fileContent);          // undefined here - how can I have fileContent defined here?

}

如果最好在纯 JS 中使用 XMLHttpRequest,那很好,但我只想知道如何使值在检索函数之外存在 - 例如,与其他函数一起使用。

关于我缺少什么的任何想法?

任何帮助将不胜感激。

【问题讨论】:

  • jQuery $.get 函数是异步的。因此,内部代码在 $.get 请求发生后运行,但 JavaScript 在运行异步命令时继续执行下一个命令。第二个警报在 $.get 完成之前运行。这就是混乱吗?
  • 我明白了——是的,确实如此。完全忘记了异步问题。非常感谢!

标签: javascript jquery scope xmlhttprequest


【解决方案1】:

$.get() 函数异步工作,因此 fileContent 不包含响应。

window.onload = function(){

  var refFile = "./myFile"; // path to my txt file
  var fileContent;

  $.get(refFile, function(response) {
    // do something here
  }).done(function(response){
    fileContent = response;
  });

  alert(fileContent); // not undefined anymore

}

看看documentation

【讨论】:

  • 谢谢你 - 我自己也试过了,但它似乎不起作用。不过真的不知道为什么。
【解决方案2】:

这段代码应该适合你。

var refFile = "./myfile"; // path to my txt file
function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readBody(xhr));
    }
}
xhr.open('GET', refFile, true);
xhr.send(null);

【讨论】:

  • alert(filecontent); 也会失败...因为 XMLHttpRequest() 也是异步的。
  • 你是对的。我修复了我的代码。
  • 编辑:刚刚看到您修复了代码 - 谢谢。那么我必须在该函数中使用文件内容的想法是什么?换句话说,我应该期望它仅在该范围内可用还是可以在 xhttp.send(null) 部分之后使用它?
  • @devEngine 我编辑了我的代码并进行了测试。它对我有用。
  • 哈!那成功了。非常感谢你的帮助!非常感谢。
猜你喜欢
  • 2016-09-26
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多