代码之家  ›  专栏  ›  技术社区  ›  aitor

将javascript变量升级到全局范围[重复]

  •  -1
  • aitor  · 技术社区  · 7 年前

    var locations;
    
    $.getJSON(themeUri + '/resources/location.json', function(result){
      locations = result;
      console.log(locations); // it shows right results.
    });
    
    console.log(locations); // undef
    

    locations 不在全局范围内。正如我所读到的,这是因为异步函数。

    所以,我试着:

    var locations;
    
    function jsonCallback(result){
      locations = result;
    }
    
    $.getJSON(themeUri + '/resources/location.json', jsonCallback);
    

    也不管用。如何将JSON内容放入全局变量中?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Andy Hoffman    7 年前

    您最初的示例中的问题是 console.log 发生在 async

    // 1. declaration happens
    var locations;
    
    // 3. this happens
    $.getJSON(themeUri + '/resources/location.json', function(result){
      locations = result;
      console.log(locations); // it shows the right results.
    });
    
    // 2. console.log happens
    console.log(locations); // undefined
    

    所以这是有道理的 2. 未定义,因为回调尚未发生。

    var locations;
    
    function fillLocations(responseJSON) {
      locations = responseJSON;
      console.log(locations); 
      // Continue to next operation…
    }
    
    $.getJSON( 'https://jsonplaceholder.typicode.com/todos/1', function(result){
      fillLocations(result);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    推荐文章