【问题标题】:proper way to fill js variables via ajax request通过ajax请求填充js变量的正确方法
【发布时间】:2013-04-25 14:35:29
【问题描述】:

目前我正在使用以下方式用 json 获取的数据填充我的全局 js 变量:

var tranlationJson =
  $.ajax({
    type: "GET",
    url: "translation.xml",
    contentType: "text/xml",
    dataType: "xml",
    success: function (dataSource) {            
            tranlationJson=ToJasonParser(dataSource);
    }
});

还有更聪明的方法吗?我需要填充这些变量,因为在稍后加载的脚本中我使用它们的内容。

【问题讨论】:

  • 那不行;它是异步的。使用承诺。

标签: javascript xml ajax json


【解决方案1】:

您可以像这样将 tranlationJson 设为对象而不是变量:

var tranlationJson = {
    init: function(){
              $.ajax({
                  type: "GET",
                  url: "translation.xml",
                  contentType: "text/xml",
                  dataType: "xml",
                  success: function (dataSource) {            
                      this.data = ToJasonParser(dataSource);
                  }
              });
}

然后像这样调用init函数:

tranlationJson.init();

然后你可以像这样访问Json response data

tranlationJson.data.something;

Demo

【讨论】:

  • 那么正确的方法是什么?我不确定我们中的许多人都知道如何使用 Promise,如果您添加一个解释它的答案,我将不胜感激。
猜你喜欢
  • 2015-08-16
  • 1970-01-01
  • 2019-01-07
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 2015-10-08
  • 2015-06-15
相关资源
最近更新 更多