0

私は私の人生のためにこれを理解することはできません。ajaxが呼び出しを行う非同期の方法に問題があることはわかっていますが、それでも問題を特定することはできません。私はこれを持っています:

$(document).ready(function() {
  $('#address').blur(function() {
    console.log("now processing address");
    var add = $("#address").val();
    console.log("address is: " + add);
    var refAdd = processAddress(add);
    console.log("refined addres is: " + refAdd);
  }); 
});

そして、呼び出している processAddress 関数があります (SO に関する別の投稿のおかげです)。問題は、上記の最後のステートメントが refAdd を未定義として返すことです。何故ですか??

function processAddress(address){
  var geocoder = new google.maps.Geocoder();
  if (geocoder) {
    geocoder.geocode({ 'address': address }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        //console.log(results[0].geometry.location);
        console.log(results[0].formatted_address);
        console.log("latitude is: " + results[0].geometry.location_type);
      }
      else {
        console.log("Geocoding failed: " + status);
        //formatted_address = "Geocoding failed: " + status;
        formatted_address = "failed"
      }
    });
  } 
}

非同期の問題であることは明らかです。出力がどのように印刷されるかの順序で見ることができます。refAdd は最後に出力する必要がありますが、そうではありません。

now processing address
address is: 415 N Mathilda Ave, Sunnyvale
refined addres is: undefined
415 N. Mathilda Ave, Sunnyvale, CA, USA
latitude is: ROOFTOP
4

1 に答える 1

0

そうです、問題は関数が非同期であるためです(どうすればそれを知ることができますか?あなたが言ったように:logs非同期で記述され、コールバック geocoder.geocode使用するため)。次のように、コールバックを使用する必要があります。

$(document).ready(function() {
  $('#address').blur(function() {
    console.log("now processing address");
    var add = $("#address").val();
    console.log("address is: " + add);

    // adding callback to call.
    processAddress(add, function(refAdd) {
      console.log("refined addres is: " + refAdd);
    });
  }); 
});

そして関数内:

function processAddress(address, callback){ // <---- note the callback arg
  var geocoder = new google.maps.Geocoder();
  if (geocoder) {
    geocoder.geocode({ 'address': address }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        //console.log(results[0].geometry.location);
        console.log(results[0].formatted_address);
        console.log("latitude is: " + results[0].geometry.location_type);
        callback('TEST'); // <---- pass here the value you need
      }
      else {
        console.log("Geocoding failed: " + status);
        //formatted_address = "Geocoding failed: " + status;
        formatted_address = "failed"
        callback('TEST'); // <---- pass here the value you need
      }
    });
  } else {
    callback(); // <---- pass here for example error if you need
  }
};

私はこのようなことを知らないgeocoderので、自分のニーズに合わせてこれをカスタマイズする必要があります.

于 2012-07-03T07:57:36.773 に答える