简体   繁体   中英

JavaScript scoping in jQuery

    function getData(jsonAddress) {
      var data = new Array();
      var xhr = $.getJSON(jsonAddress, function(meas) {
        for (var i = 0; i < meas.length ; i++) {
          var dt = datetimeSplitter(meas[i].valuedate);
          data[i] = [Date.UTC(dt[0],dt[1]-1,dt[2],dt[3],dt[4],dt[5]),parseInt(meas[i].value,10)];
        };
      });
      alert(data);
    }

I would like to make the variable "data" available to the function getData so I can return it (in this case alert). I understood it is a problem of scope, and can be solved with closure. I understood also what is a closure, but definitely don't know the syntax for this specific case.

It's not a problem of scope, it's a problem of asynchronous callbacks.

You need to pass in a callback function to this method, in order to get the response of your getJSON() call.

$.getJSON(jsonAddress, function(meas)....是异步调用,即在调用回调函数(其中数据设置有响应值)之前将调用alert语句。 ,您将看到它具有正确的值。

如果您确实不能像以前建议的那样多次使用异步调用,则也可以使用($ .ajax)[http://api.jquery.com/jQuery.ajax/]-$ .getJSON只是一个它的变体-使其同步-请注意,这不是建议的方法,因为在浏览器同步检索数据时,您的应用程序将被阻塞。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM