从 ajax 调用返回一个值到父函数 [英] Return a value from an ajax call to parent function

查看:27
本文介绍了从 ajax 调用返回一个值到父函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我需要返回一个通过 ajax 调用获得的 url.

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 调用是异步的,所以我理解为什么上面的代码会返回未定义的 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 请求是异步的,所以你唯一的选择就是使用回调.如果您可以向父"(实际上是调用")函数返回一个值,那么请求就不会是异步的;它会阻止调用函数.此外,无法从该函数的闭包中获取对调用函数的引用.(即,您不能 return 到调用堆栈中更高的函数).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆