返回从父函数调用Ajax的值 [英] Return a value from an ajax call to parent function
问题描述
我有一个功能,我需要返回一个网址,我通过Ajax调用我得到。
I have a function where I need to return a url that I am getting via an ajax call.
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
});
显然,Ajax调用是异步的,所以我理解为什么上面的code将返回tileURL为未定义。我知道,一般人用的回调函数来解决这个问题,但我不知道如何让一个回调返回一个值给父功能。我正在使用谷歌地图API,所以我真的没有任何灵活地改变是如何工作的。
Obviously, the ajax call is asynchronous so I understand why the above code will return tileURL as undefined. 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.
推荐答案
由于Ajax请求是异步的,你唯一的选择是使用一个回调。如果你能返回一个值父(实际上是呼唤)功能,则该请求将不会是异步的;它会阻塞调用函数。此外,也没有办法从在该函数中的封闭件内获得一个参考到调用函数。 (也就是说,你不能返回
来一个较高的功能在调用栈)。
Because the Ajax request is asynchronous, your only option is to use a callback. 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. (i.e., you can't return
to a function higher up in the call stack).
这篇关于返回从父函数调用Ajax的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!