jQuery中的AJAX回调返回值处理 [英] AJAX callback return value handling in jQuery
问题描述
我有这个简单的函数,可以从mapquest中获取gis数据:
I have this simple function that fetches gis data from mapquest:
function reverseGeocoding(lat,lng){
var url = 'http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat=' + lat + '&lon=' +lng+' &zoom=18&addressdetails=1';
$.ajax({
url: url,
crossDomain:true,
success: function(response){
$("#revgeo-place").html(response.display_name);
}
});
}
如何改进它,以便当从另一个函数调用此函数时,返回值被异步更新?
How can I improve it so that when this function is called from another function the return value is updated asynchronously?
我不想在函数中显式放置任何DOM引用,并且我想保持ajax异步,理想情况下应该是这样的:
I don't want to explicitly put any DOM reference in the function, and I want to keep the ajax asynchronous, ideally should be something like this:
$("#revgeo-place").html(reverseGeocoding(lat,lng).display_name);
function reverseGeocoding(lat,lng){
var url = 'http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat=' + lat + '&lon=' +lng+' &zoom=18&addressdetails=1';
$.ajax({
url: url,
crossDomain:true,
success: function(response){
console.log(response);
return response;
}
});
}
看起来,执行此操作后DOM对象不会更新,此后函数将返回响应.
It looks that when I do this the DOM object does not update, and after then the function returns the response.
任何想法都会对您有所帮助!
Any ideas would be helpful thanks!
推荐答案
您可以使用回调:
function reverseGeocoding(lat,lng, callback){
var url = 'http://open.mapquestapi.com/nominatim/v1/reverse?format=json&lat=' + lat + '&lon=' +lng+' &zoom=18&addressdetails=1';
$.ajax({
url: url,
crossDomain: true,
success: callback
});
};
reverseGeocoding(lat,lng, function(response){
$("#revgeo-place").html(response.display_name);
});
因此您的 reverseGeocoding
函数与DOM无关.
So your reverseGeocoding
function is agnostic to DOM.
这篇关于jQuery中的AJAX回调返回值处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!