2012-03-29 11 views
0

送信する前にjavascriptを使用してフォームを変更する必要があります(ユーザーが送信ボタンをクリックした後に)。このアクションには、フォームを送信する前に完了しなければならないajax呼び出しが含まれます。問題は、submitイベントハンドラが実行を終了し、ajaxが完了する前にfalseを返し、ajaxが完了した後にフォームを送信する方法を把握できなかったことです。私はこれを行うための他の方法があることを知っていますが、私はそれがこのようにする方法があるかどうかを知りたいです。ありがとう。あなたが何をしたいかajaxコールバックを使用してフォームを送信する方法を決定する方法

$("form#profile").submit(function() { 
    var dept; 
    if (IsEmpty($("input[name=dept_id1]").val())) { 
     return true; 
    } else { 
     dept = $("input[name=dept_id1]").val(); 
     $.post("funcs.php", {dept:dept}, function(d) { 
      $("select[name=dept_id]").val(d); 
      // It is at this point that I want to submit the form 
      return true; 
     }); 
    } 
    return false; 
}); 

答えて

2
$("form#profile").submit(function() { 
    var dept; 
    if (IsEmpty($("input[name=dept_id1]").val())) { 
     return true; 
    } else { 
     dept = $("input[name=dept_id1]").val(); 
     $.post("funcs.php", {dept:dept}, function(d) { 
      $("select[name=dept_id]").val(d); 
      // It is at this point that I want to submit the form 

      // unbind your submit handler 
      $("form#profile").unbind('submit'); 

      // Optionally bind a new handler here 

      // Submit it with no handler or new handler 
      $("form#profile").submit(); 

      return true; 
     }); 
    } 
    return false; 
}); 

はまた、代わりに$("form#profile")のそれはより速く、セレクタであるとして、およびIDのは、それが同じ要素を選択します一意である必要がありますので、あなたが私たち$("#profile")必要があることに注意してください。あなたはjqueryのevent.preventDefault(とそれを行うことができ

+0

感謝を返信の場合、送信ボタンを2回クリックするとフォームが送信されます。これ以上の提案はありますか? – Chibuzo

+0

@Chibuzoこれは動作しましたか? – Paulpro

+0

フォームを送信する前に[送信]ボタンを2回クリックする必要があります。 – Chibuzo

-2

は、あなたのjqueryのAJAX呼び出しにasync: falseを使用しています。 $.postでこれを行うことはできませんが、代わりに$.ajaxを実際に使用する必要があります。このような何か:

var d = $.ajax({ 
      type: 'POST', 
      async: false, 
      url: "funcs.php", 
      data: "dept="+dept, 
     }).responseText; 

$("select[name=dept_id]").val(d); 
return true; 
0

)。

http://api.jquery.com/event.preventDefault/

このブロックトリガーされたイベントから。その後、あなたはあなたが必要なすべてのものを行うことができ、最終的にはここでの例の$ .post

とポストを続行(jQueryのサイトから撮影):もっとここ

/* attach a submit handler to the form */ 
$("#searchForm").submit(function(event) { 

    /* stop form from submitting normally */ 
    event.preventDefault(); 

    /* get some values from elements on the page: */ 
    var $form = $(this), 
     term = $form.find('input[name="s"]').val(), 
     url = $form.attr('action'); 

    /* Send the data using post and put the results in a div */ 
    $.post(url, { s: term }, 
     function(data) { 
      var content = $(data).find('#content'); 
      $("#result").empty().append(content); 
     } 
    ); 
    }); 

を読む:http://api.jquery.com/jQuery.post/#example-8

関連する問題