我可以在jquery

时间:2015-08-14 00:33:52

标签: javascript jquery asp.net-mvc callback

我正在尝试阻止从提交处理程序返回false或undefined。我只想在谷歌地图返回异步结果后返回一个值。这可能吗?我的目标是在转到我的控制器之前等待谷歌地图结果回来。

$('form').submit(function (e) {
        
        var geocoder = new google.maps.Geocoder();
        var address = $('#SearchQuery').val();
        
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status != google.maps.GeocoderStatus.OK) {
                
                alert("Geocode was not successful for the following reason: " + status);
                return false;
            } else {
                $("#latitude").val(results[0].geometry.location.G);
                $("#longitude").val(results[0].geometry.location.K);
                
                alert("Geocode successful");
                return true;
            }
        });
        //don't let anything get returned here, is a callback needed?
    });

1 个答案:

答案 0 :(得分:0)

在封闭回调中使用return不会返回外部提交回调。所以基本上没有什么能阻止表单提交而不进行地理编码

您可以做的是阻止jQuery提交事件,并在地理编码成功中通过本机javascript提交提交表单,该提交不会触发jQuery版本

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

 $('form').submit(function (e) {
     // cancel the event to prevent immediate submit
     e.preventDefault();

     var form = this;
     var address = $('#SearchQuery').val();

     geocoder.geocode({
         'address': address
     }, function (results, status) {
         if (status != google.maps.GeocoderStatus.OK) {
             alert("Geocode was not successful for the following reason: " + status);

         } else {
             $("#latitude").val(results[0].geometry.location.G);
             $("#longitude").val(results[0].geometry.location.K);

             alert("Geocode successful");

             // do submit through native submit
             form.submit();

         }
     });

 });