[英]Return a value from an ajax call to parent function
I have a function where I need to return a url that I am getting via an ajax call. 我有一个函数,我需要返回通过ajax调用获取的网址。
var heatmap = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
var tileURL;
$.get('getimage.php', { zoom: zoom, x: coord.x, y: coord.y }, function(data) {
if(data.status) { tileURL=data.image; }
}, "json");
return "tileURL";
},
tileSize: new google.maps.Size(256, 256),
opacity:0.55,
isPng: true
});
Obviously, the ajax call is asynchronous so I understand why the above code will return tileURL as undefined. 显然,ajax调用是异步的,因此我理解了为什么上面的代码将返回未定义的tileURL。 I know in general people use callback functions to solve this issue, but I don't know how to get a call back to RETURN a value to the parent function.
我知道通常人们使用回调函数来解决此问题,但是我不知道如何获得回调以将值返回给父函数。 I'm working with the google maps API, so I don't really have any flexibility to change how that works.
我正在使用google maps API,因此我真的没有任何灵活性来更改它的工作方式。
Because the Ajax request is asynchronous, your only option is to use a callback. 因为Ajax请求是异步的,所以您唯一的选择是使用回调。 If you could return a value to the "parent" (really, "calling") function, then the request wouldn't be asynchronous;
如果您可以将值返回给“父”(实际上是“调用”)函数,则请求将不是异步的; it would block the calling function.
它会阻止调用函数。 Also, there is no way to get a reference to the calling function from within a closure in that function.
同样,也无法从该函数的闭包内部获取对调用函数的引用。 (ie, you can't
return
to a function higher up in the call stack). (即,您不能
return
到调用堆栈中较高的函数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.