繁体   English   中英

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

[英]Javascript function on submit button - Wait for it to complete

我想在窗体上按下提交按钮并等待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;

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

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

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

您可以拦截表单提交,中止并将地理编码请求发送给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);
            }


        });        

    });   

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

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

在这里你需要调用myFunction onSubmit事件。

正如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;
    }
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM