按钮的Ajax请求时一次点击两次提交的解决方法 转

转自https://www.jb51.net/article/93452.htm

页面中的按钮的type是submit的: <input type="submit" value="Create" id="submit" />

ajax的请求,在JQuery中是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$(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);
}
});
}
});
});

发生两次提交的原因是在执行完ajax请求后,并没有阻止submit的行为,所以解决方法有两种:

1、不使用type为submit类型的按钮,而是使用type是button的按钮。

2、在$('#submit').click函数中,最后加一行return false;,即可阻止submit。

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注