与以下问题相关。
Empty variables when calling javascript function
我正在寻求关于如何确保从ajax调用中获得所有结果的一些指导。
特别是,这次问题出在getPublicIPAddress()
函数及其ajax调用上。
function genericYiiLocation(callback) {
//console.log('genericYiiLocation: Creating location handler');
this.longitude= '';
this.latitude= '';
this.accuracy= '';
this.publicIpAddress= '';
var me = this;
if (Modernizr.geolocation) {
//console.log('genericYiiLocation: Location supported');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locateSuccess, locateFail);
} else {
alert('genericYiiLocation: Geolocation is not supported in your current browser.');
callback(false);
}
} else {
alert ('genericYiiLocation: no native location support');
callback(false);
}
GetPoo();
function GetPoo(getPublicIPAddress){
console.log(this.accuracy);
}
function locateSuccess(loc){
// console.log('genericYiiLocation: storing location data');
me.longitude = loc.coords.longitude;
me.latitude = loc.coords.latitude;
me.accuracy = loc.coords.accuracy;
callback(true, me);
}
// Unsuccessful geolocation
function locateFail(geoPositionError) {
switch (geoPositionError.code) {
case 0: // UNKNOWN_ERROR
alert('An unknown error occurred, sorry');
break;
case 1: // PERMISSION_DENIED
alert('Permission to use Geolocation was denied');
break;
case 2: // POSITION_UNAVAILABLE
alert('Couldn\'t find you...');
break;
case 3: // TIMEOUT
alert('The Geolocation request took too long and timed out');
break;
default:
}
callback(false, geoPositionError);
}
function getPublicIPAddress(callback)
{
var ip;
$.ajax({
type: 'GET',
url: 'http://smart-ip.net/geoip-json?callback=?',
dataType: 'json',
async: true ,
success: function(data) {
ip = data.host;
callback(false,ip);
}
});
//callback();
}
}
答案 0 :(得分:0)
Ajax中的“A”代表异步。这意味着AJAX调用在一段时间后完成,你javascript继续执行。您将知道AJAX调用何时完成,并且数据仅在完成事件中可用。
因此,您不能使用异步AJAX调用来获取某些数据,让您的javascript等待响应而不再执行,获取响应然后继续执行。 Javascript / asynch AJAX不能那样工作。
相反,您必须重新构建代码的工作方式,以便发出AJAX调用,然后所有需要AJAX调用响应的代码都必须放入AJAX完整回调中。
所以,你不能这样做(伪代码):
some code
var ipAddress = AJAX call to get the IP address
some code that uses the ipAddress
相反,你必须构建这样的事情:
some code
AJAX call to get the ipAddress(function(data) {
// completion callback
code that uses the response from the AJAX call
})
no code here that relies on the AJAX response because it hasn't happened yet