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/async AJAX はそのようには機能しません。

代わりに、AJAX 呼び出しを発行し、AJAX 呼び出しからの応答を必要とするすべてのコードを AJAX complete コールバックに入れる必要があるように、コードの動作を再構築する必要があります。

したがって、これを行うことはできません (疑似コードで):

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 に答える