我想发送一个表单并保持在同一个网页上,为此我正在使用jQuery和ajax,我的代码是:
$(document).on('submit', '.commentSubmit', function() {
var el = $(this);
var message = el.children('textarea').val();
if(message == '') {
alert('you can\'t send an empty message');
return false;
} else {
$.ajax({
url: el.attr('action'),
type: el.attr('method'),
data: el.serialize(),
success: function() {
alert('ok');
}
});
return false;
}
});
所以它运作良好但现在我想使用一个函数,所以我正在做:
sendMess = function(el){
var message = el.children('textarea').val();
if(message == '') {
alert('you can\'t send an empty message');
return false;
} else {
$.ajax({
url: el.attr('action'),
type: el.attr('method'),
data: el.serialize(),
success: function() {
alert('ok');
}
});
return false;
}
}
$(document).on('submit', '.commentSubmit', function() {
sendMess($(this));
});
但现在当我提交表格时,我将离开当前页面
答案 0 :(得分:3)
通过在处理程序中返回false来取消默认的提交操作。
$(document).on('submit', '.commentSubmit', function() {
sendMess($(this));
return false;
// can also do "return sendMess($(this));", but less clear
});
答案 1 :(得分:0)
$(document).on('submit', '.commentSubmit', function(event) {
sendMess($(this));
event.preventDefault()
});
答案 2 :(得分:0)
尝试:
$(document).on('submit', '.commentSubmit', function() {
return sendMess($(this));
//Or return false;
});