简体   繁体   English

处理ajax异步调用

[英]handling ajax async calls

Related to the following question. 与以下问题有关。

Empty variables when calling javascript function 调用javascript函数时为空变量

I'm seeking some guidance on how to ensure I get all results from ajax calls. 我正在寻求有关如何确保从ajax调用中获得所有结果的指导。

In particular, this time the problem is with the getPublicIPAddress() function and its ajax call. 特别是,这次问题出在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();        

}


}

The "A" in Ajax stands for asynchronous. Ajax中的“ A”代表异步。 That means that the AJAX call is finished some time later and you javascript continues executing. 这意味着AJAX调用将在一段时间后结束,并且您的javascript将继续执行。 You will known when the AJAX call is done and the data is available ONLY by the completion event. 您将知道何时完成AJAX调用,并且只有完成事件才可以使用数据。

So, you can't use an asynchronous AJAX call to fetch some data, have your javascript wait for the response and not execute any more, get the response and then continue executing. 因此,您不能使用异步AJAX调用来获取一些数据,让您的JavaScript等待响应而不再执行,获取响应然后继续执行。 Javascript/asynch AJAX doesn't work that way. Javascript /异步AJAX不能那样工作。

Instead, you have to restructure how your code works so that you issue the AJAX call and then all code that needs the response from the AJAX call must be put into the AJAX complete callback. 相反,您必须重组代码的工作方式,以便发出AJAX调用,然后,需要AJAX调用响应的所有代码都必须放入AJAX完整回调中。

So, you can't do this (in pseudo code): 因此,您不能执行此操作(使用伪代码):

some code
var ipAddress = AJAX call to get the IP address
some code that uses the ipAddress

Instead, you have to structure things like this: 相反,您必须构建如下结构:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM