2012-10-29 65 views
0

在一個巨大的web應用程序中,我需要一個提交表單的解決方法。覆蓋javascript標準提交函數行爲

爲了覆蓋內置的javscript方法,我嘗試了this example,但我甚至沒有彈出警報。

我對覆蓋提交功能的想法是這樣的:

function submit(event) { 
     var target = event ? event.target : this; 
     $.ajax({ 
      url: target.action, 
      data: $('form').serialize(), // &nd someone knows how I can get the serialize() of the form I just clicked? 
      success: function (data) { 
       alert('done'); 
      }, 
      error: function (data) { 
       alert('error (check console log)'); 
       console.log(data); 
      } 
     }); 
     //this._submit(); 
     return false; 
    } 

到處使用的提交的方式是不相符的。原始代碼中的可能性:

<button onclick="form.submit"> 
onclick="calltoFunction();" // where inside the function the submit is called 
<button type="submit" // the normal way 

我想我的想法是可能的,因爲我之前覆蓋了js-functions。但是,我應該如何使用提交部分來完成。 歡迎任何建議,想法和修復!

+0

你在ajax函數中沒有** type ** attr! – Jai

+0

我確實在ajaxsetup中。對不起,不提。也試着把它放在函數中,沒有結果。 – user1469734

回答

2

綁定的事件,你的按鈕,像這樣:

$('#my_button').click(
    function(event){ 
     event.preventDefault(); //This will prevent the buttons default submit behavior 
     ...//The rest is up to you! 
} 
); 
+0

jquery不是給定的 – Jasper

+1

這是在他的代碼示例。 – Hippocrates

+0

我的不好,我看了一下那些重要的代碼部分,並沒有看到它。 – Jasper

0
function submit(form) { 
    $.ajax({ 
     url: $(form).attr('action'), 
     data: $(form).serialize(), 
     success: function (data) { 
      alert('done'); 
     }, 
     error: function (data) { 
      alert('error (check console log)'); 
      console.log(data); 
     } 
    }); 
    return false; 
} 

<form id="my-form" action="/my-action-file.php" method="post" onsubmit="return submit('#my-form');"> 
    <!-- my form content --> 
</form> 
+0

這確實是一件簡單的事情,但在這種情況下不是一種選擇,請參閱startpost,但感謝您的努力。 – user1469734

0

我懷疑你會發現這個有用:

$('#yourForm').beforeSubmit(function() 
{ 
    return doWhateverYouLikeAndReturnTrueToContinueFormSubmition($(this)); 
}); 

這將任何其他形式提交代碼之前執行doWhateverYouLikeAndReturnTrueToContinueFormSubmition

+0

之前沒有看到該功能。但我想要的是用Ajax發送數據。在這種情況下不能用beforeSubmit。我仍然應該在該功能之後提交表格。 – user1469734

+0

我沒有看到什麼會阻止你從'doWhateverYouLikeAndReturnTrueToContinueFormSubmition()' –

+0

做AJAX調用我想覆蓋原來的提交函數。所以不使用ID。由於該應用程序有大量表單,並且他們需要快速的解決方法來通過ajax提交它們。或者我錯了? – user1469734

0

你可以試試這個:

function submit(event) { 
    var target = event ? event.target : this; 
    $.ajax({ 
     url: target.action, 
     type: "POST", 
     data: $('form').serialize(), // &nd someone knows how I can get the serialize() of the form I just clicked? 
     success: function (data) { 
      alert('done'); 
     }, 
     error: function (data) { 
      alert('error (check console log)'); 
      console.log(data); 
     } 
    }); 
    //this._submit(); 
    return false; 
    } 
+0

我已經在Ajaxsetup中定義了Post的類型。 – user1469734