【问题标题】:Assigning read yaml file to variable in browser to be used in jquery将读取的 yaml 文件分配给浏览器中的变量以在 jquery 中使用
【发布时间】:2018-01-19 22:49:37
【问题描述】:

我正在尝试解析作为文件系统中的本地文件存在的 yaml 文件,并将其分配给可在 jquery 中使用的变量。 我可以从 console.log 看到 _yaml 变量包含可读格式的读取 yaml,但返回它并将其分配给 ymlconfig 似乎不起作用(//NOT WORKING 下面的部分在控制台中显示为未定义)。

$( document ).ready(function() {
    var ymlconfig = read_config('config.yaml');
    console.log(ymlconfig["compute"][0]); //NOT WORKING

    function read_config(cfgfile) {
        $.get({url: cfgfile, dataType: "text"}).done(function (data) {
            var _yaml = jsyaml.load(data);
            console.log(_yaml["compute"][0])  //WORKING OK
            return _yaml;
        });
    };

【问题讨论】:

  • 请仔细阅读问题中的文字并进行编辑以提出明确的问题。很难理解问题是什么,你遇到了什么,以及你希望完成什么。

标签: javascript jquery yaml


【解决方案1】:

这个字符串:

console.log(ymlconfig["compute"][0]); //NOT WORKING

在读取配置之前执行。因为被调用的read_config('config.yaml') 在单独的线程中异步运行。

您的function read_config(cfgfile) 也不返回任何值。

为了更好地理解这种行为,请阅读并运行以下代码:

$( document ).ready(function() {
   var ymlconfig;
   read_config('config.yaml'); // calling function
   console.log(ymlconfig["compute"][0]); // is empty

   setTimeout(function() { // let's wait 2000 ms. hope it's enough to send the request and receive and read the response
      console.log(ymlconfig["compute"][0]); // TADA! It's read.
   }, 2000);

   function read_config(cfgfile) {
      $.get({url: cfgfile, dataType: "text"})
       .done(function (data) {
          ymlconfig = jsyaml.load(data);
      });
   };
});

因此,根据您的任务,您有多种选择:

.done回调函数中处理配置数据,
或使您的请求同步,
或捕获异步响应(例如使用承诺) 或者别的什么?

【讨论】:

  • 在读取配置之前执行是什么意思?我正在调用函数来阅读它? “你的函数 read_config(cfgfile) 也不返回任何值。”现在我可以理解了。我曾尝试在 get 之前分配一个变量,例如 var test=$.get 并返回它,但它不仅非常难看。它似乎也不起作用。我是 JavaScript 新手,所以函数中的这些函数似乎有点难以从中返回内容。
  • @nicklas,谢谢,我已经更新了我的答案,使其更加清晰。
  • 谢谢一百万。这样可行。我应该已经意识到请求的异步性质,但由于我只是加载一个本地文件,我希望立即响应。 [内联] `function read_config(cfgfile) { var rawyaml = ''; $.get({url: cfgfile, dataType: "text", async: false}).done(function (data) { rawyaml = data; console.log(rawyaml); });返回 jsyaml.load(rawyaml); }; ` [/inline] 为我完成这项工作。
猜你喜欢
  • 1970-01-01
  • 2016-11-19
  • 2013-07-15
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
相关资源
最近更新 更多