2012-03-29 23 views
0

我想在我提交它之前使用javascript修改表单(在用户必须点击提交按钮之后)。该行动涉及一个Ajax调用,在我提交表单之前必须完成。问题是,在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")你应该我们$("#profile"),因为它是一个更快的选择,并且由于ID的应该是唯一会选择相同的元素。

+0

谢谢对于答复,表单仅在我点击提交按钮两次时提交。还有什么建议? – Chibuzo 2012-03-29 19:34:13

+0

@Chibuzo你有这个工作吗? – Paulpro 2012-03-29 20:58:57

+0

我必须在表单提交前点击两次提交按钮。 – Chibuzo 2012-03-30 00:48:57

-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

你可以做到这一点与jQuery的event.preventDefault()。

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

该块被触发事件。然后,你可以做你需要的所有东西,并最终继续后用$。员额

下面是一个例子(从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