Return a value from an ajax call to parent function(从 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 调用返回一个值到父函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 ajax 调用返回一个值到父函数


- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01