从 ajax 调用返回一个值到父函数

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)