获取到ajax异步请求的数据的方法

// 通过GPS坐标取城市名
function getCityNameByLocation(lng, lat, callback) {
// 参考:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
$.ajax({
url: '//api.map.baidu.com/geocoder/v2/',
type: 'GET',
data: {
ak: 'eNb809Xt5UBLLxCGKkmj6IOdEfwQyhwM',
coordtype: 'wgs84ll',
location: lat + ',' + lng,
output: 'json'
},
dataType: 'jsonp',
success: function(res) {
var cityName = '';
if (res && res.status === 0 && $.isPlainObject(res.result) && $.isPlainObject(res.result.addressComponent) && res.result.addressComponent.city) {
cityName = res.result.addressComponent.city.replace('市', '');
}
callback.call(this, cityName);
}
});
}

function init() {
if ($.cookie('gps_cache')) {
return;
}
getGeoLocation(function(lng, lat) {
getCityNameByLocation(lng, lat, function(cityName) {
if (cityName) {
setGpsCacheCountdown();
setCity(cityName, lastGpsCity);
} else {
getLocationFailedHandler();
}
});
});
}

init();

// 设置城市
function setCity(gpsCity, lastGpsCity) {
$.cookie('gps_city', gpsCity, {
expires: 365,
path: '/'
});

if (lastGpsCity) {
// 定位城市发生变化
if (lastGpsCity !== gpsCity) {
switchCity(gpsCity);
}
} else {
// 初次打开首页时,定位城市和显示城市不同
var shownCity = $.cookie('shown_city');
if (shownCity && shownCity !== gpsCity) {
switchCity(gpsCity);
}
}
}

原文地址:https://www.cnblogs.com/allenda/p/6610892.html