如何使用ajax回调来确定何时提交表单


How to use ajax callback to determine when to submit form

在提交表单之前,我想使用javascript修改表单(在用户必须单击提交按钮之后)。该操作涉及一个ajax调用,必须在我提交表单之前完成。问题是submit事件处理程序将在ajax完成之前完成执行并返回false,我还不知道如何在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;
});
$("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;
});

还要注意,您应该使用$("#profile")而不是$("form#profile"),因为它是一个更快的选择器,并且由于id应该是唯一的,因此它将选择相同的元素。

您可以使用jquery event.prventDefault().来实现这一点

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

http://api.jquery.com/ajaxComplete/

您想要做的是在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;