0

与以下问题有关。

调用javascript函数时为空变量

我正在寻求一些关于如何确保从 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();        

}


}
4

1 回答 1

0

Ajax 中的“A”代表异步。这意味着 AJAX 调用会在一段时间后完成,并且您的 javascript 会继续执行。您将知道 AJAX 调用何时完成并且数据仅在完成事件中可用。

因此,您不能使用异步 AJAX 调用来获取一些数据,让您的 javascript 等待响应并且不再执行,获取响应然后继续执行。Javascript/异步 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
于 2013-01-16T16:13:38.263 回答