0

我想在表单上按下提交按钮时触发一个函数并等待javascript函数完成,然后继续表单提交。我不希望在 javascript 函数完成之前提交表单。**

这就是我目前所拥有的:http: //jsfiddle.net/njDvn/68/

function autosuggest() {
var input = document.getElementById('location');
    var options = {
    types: [],
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);
}

<!-- Get lat / long -->      
function getLatLng() {
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('location').value;
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latLng = results[0].geometry.location;
            $('#lat').val(results[0].geometry.location.lat());
            $('#lng').val(results[0].geometry.location.lng());
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

<!-- Load it --> 
window.onload = autosuggest;
4

4 回答 4

1

首先你需要防止表单被提交,在函数return false末尾添加一个。getLatLng()

然后当地理编码完成后,手动提交表单document.getElementsByTagName('form')[0].submit()

这是一个更新的 jsfiddle:http: //jsfiddle.net/njDvn/70/

于 2012-11-04T00:21:40.473 回答
1

您可以拦截表单提交、中止它并将地理编码请求发送给 Google。

当服务器响应时,您可以从回调中重新提交表单(或在失败的情况下显示错误)。

将请求的状态存储在某处(为简单起见,我在示例中使用了全局变量)。在这种情况下,它只是一个指示地理编码请求是否成功完成的标志(所以现在,当提交表单并重新触发侦听器时,它将知道不重新发送地理编码请求)。

http://jsfiddle.net/njDvn/75/

随意删除控制台日志记录。

您可能还希望隐藏纬度/经度字段。

var GeoCoded = {done: false}; // this holds the status of the geo-coding request

$(document).ready(function(){
    autosuggest(); // place your auto-suggest (now called autocomplete) box

    $('#myform').on('submit',function(e){

        if(GeoCoded.done)
            return true;

        e.preventDefault();
        console.log('submit stopped');
        var geocoder = new google.maps.Geocoder();
        var address = document.getElementById('location').value;

        // disable the submit button
        $('#myform input[type="submit"]').attr('disabled',true);

        // send the request
        geocoder.geocode({
            'address': address
        },
        function (results, status) {
            // update the status on success
            if (status == google.maps.GeocoderStatus.OK) {
                var latLng = results[0].geometry.location;
                $('#lat').val(results[0].geometry.location.lat());
                $('#lng').val(results[0].geometry.location.lng());
                // if you only want to submit in the event of successful 
                // geocoding, you can only trigger submission here.
                GeoCoded.done = true; // this will prevent an infinite loop
                $('#myform').submit();
            } else { // failure
                console.log("Geocode was not successful for the following reason: " + status);
                //enable the submit button
                $('#myform input[type="submit"]').attr('disabled',false);
            }


        });        

    });   

});
于 2012-11-04T00:54:36.210 回答
0
myFunction = new function(callback) {
    $.ajax({...}).done(callback());
}

myFunction(new function() {
    getLatLng();
});

这里需要调用myFunctiononSubmit 事件。

于 2012-11-04T00:19:22.737 回答
0

正如 MasterAM 所说,您需要做的就是以下几点:

/// I've included the following function to allow you to bind events in a 
/// better way than using the .onevent = function(){} method.
var addEvent = (function(){
  if ( window.addEventListener ) {
    return function(elm, eventName, listener, useCapture){
      return elm.addEventListener(eventName,listener,useCapture||false);
    };
  }
  else if ( window.attachEvent ) {
    return function(elm, eventName, listener){
      return elm.attachEvent('on'+eventName,listener);
    };
  }
})();

/// add another window.onload listener
addEvent(window,'load',function(){
  /// find the form, obviously should use whatever id you have on your form
  var form = document.getElementById('my_form');
      form.preventSubmit = true;
  /// add our onsubmit handler
  addEvent(form,'submit',function(e){
    /// only stop the form if we haven't already
    if ( form.preventSubmit ) {
      /// place/call whatever code you need to fire before submit here.
      alert('submit was blocked!');
      /// after that code is complete you can use the following
      form.preventSubmit = false;
      form.submit();
      /// return false prevents the submit from happening
      return false;
    }
  });
});
于 2012-11-04T00:31:28.950 回答