提交按钮上的Javascript函数 - 等待它完成

时间:2012-11-03 23:19:43

标签: javascript

我想在表单上按下提交按钮并等待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 个答案:

答案 0 :(得分:1)

首先,您需要阻止提交表单,在return false函数末尾添加getLatLng()

然后在完成地理编码后,使用document.getElementsByTagName('form')[0].submit()

手动提交表单

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

答案 1 :(得分: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);
            }


        });        

    });   

});

答案 2 :(得分:0)

myFunction = new function(callback) {
    $.ajax({...}).done(callback());
}

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

您需要在此提交myFunction onSubmit事件。

答案 3 :(得分: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;
    }
  });
});