簡體   English   中英

我可以在jquery中使用帶.submit的回調嗎

[英]Can I use a callback with .submit in jquery

我試圖防止從提交處理程序返回false或undefined。 我只想在異步結果從Google地圖返回后返回一個值。 這可能嗎? 我的目標是要等到Google地圖結果返回后再轉到控制器。

 $('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? }); 

在封閉的回調中使用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();

         }
     });

 });

暫無
暫無

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

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