簡體   English   中英

Javascript / jQuery-等待功能完成,然后再運行其余功能

[英]Javascript/jQuery - waiting until function complete before running the rest

嗨,我有一個按鈕,單擊該按鈕會觸發一個功能。 該函數會做一些事情(對緯度/經度進行反向地理編碼),然后用值填充隱藏的表單輸入。

在需要執行的其余代碼之前,我需要輸入具有正確的值,有沒有辦法做到這一點? 此刻我有

$('.addButton').click(function() { 
    //first run the reverse geocode to update the hidden location input with the readable address
    reversegeocode();
    var location = $("#location").val();//the value I need
    $.post("<?php echo $this->webroot;?>locations/add", {location:location})
        .done(function (data) {
            $("#locationsHolder").html(data);
        });
});

所以基本上我不想從輸入中獲取值並通過AJAX將其發布,直到我知道reversegeocode()函數完成為止

誰能解釋一下我該怎么做。 我已經閱讀了一些有關延期的內容,但是我對弄清Javascript毫無用處,我真的很努力。

謝謝

編輯:

這是我的反向地理編碼功能

function reversegeocode(){
    var lat = $('#lattitude').val();
    var lng = $('#longitude').val();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[0]) {//http://stackoverflow.com/questions/8082405/parsing-address-components-in-google-maps-upon-autocomplete-select
              var address_components = results[0].address_components;
              var components={}; 
                jQuery.each(address_components, function(k,v1) {jQuery.each(v1.types, function(k2, v2){components[v2]=v1.long_name});})
            var output = '';
            var needAcomma = false;
            if(components.route != undefined) {
                output += components.route;
                needAcomma = true;
            }
            if(components.locality != undefined) {
                if(needAcomma) {
                    output += ', ';
                }
                output += components.locality;
                needAcomma = true;
            }
            if(components.administrative_area_level_1 != undefined) {
                if(needAcomma) {
                    output += ', ';
                }
                output += components.administrative_area_level_1;
                needAcomma = true;
            }else if(components.administrative_area_level_2 != undefined) {
                if(needAcomma) {
                    output += ', ';
                }
                output += components.administrative_area_level_2;
                needAcomma = true;
            }else if(components.administrative_area_level_3 != undefined) {
                if(needAcomma) {
                    output += ', ';
                }
                output += components.administrative_area_level_3;
                needAcomma = true;
            }
            $("#location").val(output);
          } else {
            alert('No results found');
          }
        } else {
          alert('Geocoder failed due to: ' + status);
        }
    });
}

由於reversegeocode是異步方法,因此您需要使用基於回調的解決方案。 reversegeocode應該接收一個回調方法作為參數,然后在地理編碼完成后調用該回調。

$('.addButton').click(function () {
    //pass a callback to reversegeocode which will get called once the geocoding is completed
    reversegeocode(function (location) {
        //the callback receives the location as a parameter
        $.post("<?php echo $this->webroot;?>locations/add", {
            location: location
        })
            .done(function (data) {
            $("#locationsHolder").html(data);
        });
    });
});

function reversegeocode(callback) {
    var lat = $('#lattitude').val();
    var lng = $('#longitude').val();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) { //http://stackoverflow.com/questions/8082405/parsing-address-components-in-google-maps-upon-autocomplete-select
                var address_components = results[0].address_components;
                var components = {};
                jQuery.each(address_components, function (k, v1) {
                    jQuery.each(v1.types, function (k2, v2) {
                        components[v2] = v1.long_name
                    });
                })
                var output = '';
                var needAcomma = false;
                if (components.route != undefined) {
                    output += components.route;
                    needAcomma = true;
                }
                if (components.locality != undefined) {
                    if (needAcomma) {
                        output += ', ';
                    }
                    output += components.locality;
                    needAcomma = true;
                }
                if (components.administrative_area_level_1 != undefined) {
                    if (needAcomma) {
                        output += ', ';
                    }
                    output += components.administrative_area_level_1;
                    needAcomma = true;
                } else if (components.administrative_area_level_2 != undefined) {
                    if (needAcomma) {
                        output += ', ';
                    }
                    output += components.administrative_area_level_2;
                    needAcomma = true;
                } else if (components.administrative_area_level_3 != undefined) {
                    if (needAcomma) {
                        output += ', ';
                    }
                    output += components.administrative_area_level_3;
                    needAcomma = true;
                }
                $("#location").val(output);
                //call the callback
                callback(output);
            } else {
                alert('No results found');
            }
        } else {
            alert('Geocoder failed due to: ' + status);
        }
    });
}

更改reversegeocode采取callback參數(也稱為continuation )。

封裝了所有需要等待的東西reversegeocode到結束,把它變成一個原地的,無名的功能。

(請注意,相似到什么你已經做了click處理程序。)

使用這種方法,您還可以自由地向回調添加參數,您可以使用這些參數直接傳遞數據。

$('.addButton').click(function() { 
    reversegeocode(function(some_data) {
        var location = $("#location").val();//the value I need
        //...stuff...
    });
});

function reversegeocode(callback){
    //...stuff...
    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          //...stuff...
        } else {
          alert('Geocoder failed due to: ' + status);
        }
        callback(some_data);
    });
}

您需要在reversegeocode函數中使用回調函數。

與執行ajax相同的確切方法:)

$('.addButton').click(function() { 
    reversegeocode().done(function(location) {
        $.post("<?php echo $this->webroot;?>locations/add", {location:location})
            .done(function (data) {
                $("#locationsHolder").html(data);
            });
    });
})

為此,您將需要反向地理代碼返回一個jQuery延遲的promise

function reversegeocode() {
  return $.Deferred(function(d) {
    //do stuff and when it succeeds
    d.resolve(location);
    //or if it fails
    d.reject("something went wrong");
  }).promise();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM