【问题标题】:Javascript jQuery ajaxJavascript jQuery ajax
【发布时间】:2012-12-08 01:50:53
【问题描述】:

我正在尝试按照此 Google Maps API geocode function problem 代码使用 Google Geocode API,但我做错了。我从地理编码开始,然后是 jQuery 验证器,但不知何故,状态没有得到设置。有什么帮助吗?

jQuery(document).ready(function($) {

  var shvalidator = $('#post').validate({
    rules: {
      post_title: { required:true }
    },
    messages:  { 
        post_title: {required:jQuery.format("Enter the name of the venue")} 
    }
  });

  function getAddress() {

    var geocoder = new google.maps.Geocoder();

    var fulladdress = $('#sh_venue_address1').val()+' ' \
      +$('#sh_venue_address2').val()+' ' \
      +$('#sh_venue_city').val()+' ' \
      +$('#sh_venue_state').val()+' ' \
      +$('#sh_venue_postalcode').val();

    alert(fulladdress );
    var a,b;

    geocoder.geocode( { 'address': fulladdress},
    function(results, status) {
     //**// 
     if (status == google.maps.GeocoderStatus.OK) {
        a = results[0].geometry.location.lat();
        b = results[0].geometry.location.lng();
        setAddress(a,b);
      }
    });
  }

  // this is the callback method that waits for response from google
  function setAddress(lat,lng) {
    $('#sh_venue_latitude').val(lat);
    $('#sh_venue_longitude').val(lng);
    alert ($('#sh_venue_latitude').val());
  }

  // this is used to validate the form before submitting
  $('#post').submit(function() {
    getAddress();
    if (shvalidator.valid()==true){
      return true;
    } else {
      $('#ajax-loading').hide();
      $('#publish').removeClass('button-primary-disabled');
      return false;
    }
  });
});

【问题讨论】:

  • 做console.log(arguments),你得到了什么?
  • 我的状态未定义
  • 代码运行良好,直到 //**// 但由于状态未定义,它跳过了变量 a 和 b 的设置

标签: javascript jquery google-geocoder


【解决方案1】:

我认为它不起作用,因为函数 getAddress 在处理提交之前没有完全执行(因为它是对地址进行地理编码的异步调用)。 我想在提交功能中这样做:

getAddress(function(){
if (shvalidator.valid()==true){
      return true;
    } else {
      $('#ajax-loading').hide();
      $('#publish').removeClass('button-primary-disabled');
      return false;
    }
});

并将 getAddress 函数更改为:

function getAddress(callback){
...
setAddress(a,b);
callback();

...
}

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多