在JavaScript中通过异步调用返回对象
Returning objects through Asynchronous calls in JavaScript
我正在开发一个纯Java程序,它以文本的形式接受地址并将其传递给Google Map API以进一步打破国家,州和Zip。
但是我被困在某个地方,我的Java程序抛出一个异常,导致尴尬的结果。
现在我决定使用java与Rhino集成。这是因为我成功地开发了一个Web Page,它接受字符串并以Country,State和Zip格式解析它。所以现在我的想法是,我将这个JavaScript文件集成到我的Java文件使用Rhino。
function showLocation(address) {
var geocoder;
if(!geocoder){
alert("GC is initialised");
geocoder = new GClientGeocoder();
}
geocoder.getLocations(address , function(response)
{
if (!response || response.Status.code != 200) {alert("Sorry, unable to locate that address");}
else {
place = response.Placemark[0];
}
}//END OF CALLBACK METHOD
);//END OF GETLOCATIONS
}//end of showLocation
现在我的问题是,当我调用showLocations()
你不能!由于getLocations
是异步的,在response
可用之前,showLocation
已经完成了执行。
您需要接受showLocation
的回调。还有一些其他的问题,我将在下面解决。
function showLocation(address, callback) {
var geocoder = new GClientGeocoder(); // no need for !geocoder test--it will always be undefined!
geocoder.getLocations(address , function(response) {
if (!response || response.Status.code != 200) {
alert("Sorry, unable to locate that address");
} else {
// you forgot the "var" before "place"--you were making a global variable "place"
var place = response.Placemark[0];
if (callback) callback(place);
}
});
}
然后让用户提供一个回调,如下所示:
function placeCallback(place) {
// do something with place object here
}
showLocation('my address', placeCallback);
相关文章:
- 如何从ajax调用返回.wrap()元素
- Ajax调用返回当前html页面,而不是请求的文件
- 如何在模式框中显示ajax调用返回的数据
- AngularJS$http.post调用返回502(坏网关)错误
- 有没有更好的方法可以测量从Ajax调用返回数据所需的总时间
- 格式化AJax调用返回的Json,并将其分配给javascript变量
- calling.trigger(“click”),它在ajax调用返回的javascript代码中
- 在异步调用返回之前隐藏页面
- 对php文件的Ajax调用返回该文件中的JS代码,而不是执行它
- 如何在下一次 AJAX 调用中访问从一个 AJAX 调用返回的变量
- jQuery 延迟的 AJAX 调用返回值
- Django Ajax 调用返回 403 错误请求
- 从异步调用返回数组,然后为数组的每个元素返回其他异步调用
- 从函数返回函数而不调用返回的函数
- 当Json Length过长时,对ASP.NET MVC Controller的Ajax调用返回404
- 如何从jQuery中Ajax调用返回的数据中获取对象
- 如果statusCode不是200,那么从http调用返回什么类型的错误对象
- 如何使用jsonp调用返回的数据在Durandal中呈现视图
- 为什么我的ajax调用返回null
- 如何获取ajax调用返回的元素数