2012-03-29 59 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