2016-11-28 181 views
0

我想提交一個表單使用Ajax在ASP.NET中,一切工作正常,但我不能阻止使用e.preventdefault()方法的默認表單提交。使用Ajax在MVC中提交表單。無法防止默認表單提交

這是我的jQuery AJAX提交代碼:

$('#submitBtn').on('click', function() { 
    $('#addNewContact').submit(function (e) { 

     e.preventDefault(); 

     $.ajax({ 
      type: "POST", 
      url: $(this).attr('action'), 
      data: $(this).serialize(), 
      dataType: 'json', 
      success: function (message) { 
       console.log(message); 
      }, 
      error: function (message) { 
       console.log(message); 
      } 

     }) 


    }) 
}) 
+1

將'submitBtn'的類型更改爲普通按鈕或將代碼修改爲'$('#submitBtn')。on('click',function(e){'and'e.preventDefault();'點擊功能 – vijayP

回答

0

如果你有一個表格ID addNewContact和一個提交按鈕,然後你可以用這樣的方式來註冊它

$('#addNewContact').submit(function (e) { 

    e.preventDefault(); 

    $.ajax({ 
     // ... 
    }); 

}); 

在你代碼,你已經使用了$(this).attr('action')這意味着你正在嘗試使用表單提交事件,但是你在代碼中做錯了。你所做的是:

$('#submitBtn').on('click', function() { // Click handler registered 

    $('#addNewContact').submit(function (e) { // Submit handler registered 

     e.preventDefault(); 

     $.ajax({ 
      // ... 
     }); 

    }); 
}); 

所以,你的代碼應爲如下(爲表單提交事件):

$('#addNewContact').submit(function (e) { 

    e.preventDefault(); 

    $.ajax({ 
     type: "POST", 
     url: $(this).attr('action'), 
     data: $(this).serialize(), 
     dataType: 'json', 
     success: function (message) { 
      console.log(message); 
     }, 
     error: function (message) { 
      console.log(message); 
     } 
    }); 

}); 
+0

是的,這就是我說的,只有當他點擊按鈕時,提交處理程序纔會被註冊,但這不是預期的行爲 –

1

如果e.preventDefault()不工作,你可以寫 - 在最後陳述 - return false;該功能執行您所需的功能,並將防止默認表單提交。

+0

如果您對我提供的答案滿意,請選擇它作爲正確答案你的問題 –