这是我的代码:
$(document).ready(function(){
$("#mainbutton").click(function(){
$("#ajaxform").submit(function(e){
var info = $(this).serialize();
$.ajax(
{
url : "userctrl",
type: "post",
data : info,
success:function(data, textStatus, jqXHR)
{
console.log("success");
$('.valid-error').html(data);
},
});
e.preventDefault()
});
$("#ajaxform").submit(); //Submit the form
});
});
和我的HTML
<form id="ajaxform">
<input type="hidden" name="action" value="submit"/>
<input type="text" placeholder="Name" name="name" id="name" /><span></span>
<input type="text" placeholder="Surname" name="surname" /><span></span>
<input type="text" placeholder="Address" name="address" /><span></span>
<p class="valid-error"></p>
<input id="mainbutton" class="mainbutton" type="button" value="trial"/>
</form>
此请求会执行多次,具体取决于填充的字段。如果我填写两个字段将执行3次,如果我填写3个字段4次。情况并非总是如此,但绝对是我的servlet中的doPost方法被调用了几次....我只点击提交按钮一次!为什么?
答案 0 :(得分:2)
因为每次单击该按钮,您都会向表单添加另一个submit
处理程序。每当你发现自己从另一个事件处理程序中的中挂起一个事件处理程序时,你想要仔细考虑是否真的想要这样做(通常,它不是)。
将submmit
挂在 click
处理程序之外:
$(document).ready(function() {
$("#ajaxform").submit(function(e) {
var info = $(this).serialize();
$.ajax({
url: "userctrl",
type: "post",
data: info,
success: function(data, textStatus, jqXHR) {
console.log("success");
$('.valid-error').html(data);
},
});
e.preventDefault()
});
$("#mainbutton").click(function() {
$("#ajaxform").submit(); //Submit the form
});
});