Javascript 通过ajax请求填充js变量的正确方法

Javascript 通过ajax请求填充js变量的正确方法,javascript,xml,ajax,json,Javascript,Xml,Ajax,Json,目前,我正在使用以下方法用json获得的数据填充全局js变量: var tranlationJson = $.ajax({ type: "GET", url: "translation.xml", contentType: "text/xml", dataType: "xml", success: function (dataSource) { tranlationJson=ToJasonParser(d

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

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

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

您可以将TranslationJSON作为对象,而不是这样的变量:

var tranlationJson = {
    init: function(){
              $.ajax({
                  type: "GET",
                  url: "translation.xml",
                  contentType: "text/xml",
                  dataType: "xml",
                  success: function (dataSource) {            
                      this.data = ToJasonParser(dataSource);
                  }
              });
}
tranlationJson.init();
tranlationJson.data.something;
然后像这样调用
init
函数:

var tranlationJson = {
    init: function(){
              $.ajax({
                  type: "GET",
                  url: "translation.xml",
                  contentType: "text/xml",
                  dataType: "xml",
                  success: function (dataSource) {            
                      this.data = ToJasonParser(dataSource);
                  }
              });
}
tranlationJson.init();
tranlationJson.data.something;
然后您可以访问
Json响应数据,如下所示:

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

那是行不通的;它是异步的。使用承诺。那么什么是正确的方法呢?我不确定我们中的许多人是否知道如何使用承诺,如果您能给出解释,我将不胜感激。