頁面中的按鈕的type是submit的: <input type="submit" value="Create" id="submit" />
ajax的請求,在JQuery中是:
$(
function () {
$('#submit').click( function () {
var createGenreForm = $('#createGenreForm');
if (createGenreForm.valid()) {
var obj = {
Name: $('#Name').val(),
Description: $('#Description').val()
};
var jsonSerialized = JSON.stringify(obj);
$.ajax({
type: "POST",
url: createGenreForm.attr('action'),
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonSerialized,
success: function (result) {
alert(result.Message);
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
}
});
}
});
});
$('#submit').click( function () {
var createGenreForm = $('#createGenreForm');
if (createGenreForm.valid()) {
var obj = {
Name: $('#Name').val(),
Description: $('#Description').val()
};
var jsonSerialized = JSON.stringify(obj);
$.ajax({
type: "POST",
url: createGenreForm.attr('action'),
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonSerialized,
success: function (result) {
alert(result.Message);
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
}
});
}
});
});
發生兩次提交的原因是在執行完ajax請求后,並沒有阻止submit的行為,所以解決方法有兩種:
1、不使用type為submit類型的按鈕,而是使用type是button的按鈕。
2、在$('#submit').click函數中,最后加一行return false;,即可阻止submit。