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

フォームの送信を傍受して中止し、ジオコーディング リクエストを 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 に答える
1

まず、フォームが送信されないようにする必要があります。関数return falseの最後に a を追加しgetLatLng()ます。

次に、ジオコーディングが完了したら、フォームを手動で送信しますdocument.getElementsByTagName('form')[0].submit()

更新された jsfiddle は次のとおりです: http://jsfiddle.net/njDvn/70/

于 2012-11-04T00:21:40.473 に答える
0
myFunction = new function(callback) {
    $.ajax({...}).done(callback());
}

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

myFunctionここでonSubmit イベントを呼び出す必要があります。

于 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 に答える