[英]Ajax form send error
我有一個將數據發送到服務器的form
。 當表單是常用的HTML時,它可以正常工作。 所有數據均正確發送到服務器。 但是,當我更改表格以使用AJAX時,出現錯誤。
<form id="form" action="handler.php" method="POST"> <!-- it's work -->
<input id="contact_name" type="text" name="name" placeholder="NAME">
<input id="contact_phone" type="text" name="phone" placeholder="PHONE">
<button type="submit">Get call</button>
</form>
$(document).ready(function() {
/*this does not work*/
$('#form').on('submit', function(e) {
var dataf = $(this).serialize();
$.ajax({
url: 'handler.php',
type: 'POST',
data: dataf,
success: function(response) {
console.log(JSON.stringify(response));
},
error: function(response) {
console.log(JSON.stringify(response));
}
});
});
});
在控制台中,我得到這個:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
您必須添加e.preventDefault();
$(document).ready(function(){/*this does not work*/
$('#form').on('submit', function(e) {
e.preventDefault();
var dataf = $(this).serialize();
$.ajax({
url: 'handler.php',
type: 'POST',
data: dataf,
success: function(response) {
console.log(JSON.stringify(response));
},
error: function(response) {
console.log(JSON.stringify(response));
}
});
});
});
<button type="submit">Get call</button>
應該
<button type="button">Get call</button>
由於您是通過jQuery手動提交的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.