这是我在这里发布的第一个问题,所以如果格式不完全像它应该的那样,我提前道歉。我是JS的新手,我现在遇到了一个问题,尽管我广泛使用Google,但我仍然无法解决这个问题。
我有一个动态创建的表单,当该表单提交时,我希望将结果添加到div中,并且不会被重定向。我尝试过同时使用event.preventDefault()和return false;但它们都不起作用。ajax调用可以正常工作,因为在重定向之前,结果会在短时间内可见。如果有任何帮助,我将不胜感激。这是我的JS代码:
$(document).on('submit', '#voteForm', function(event){
event.preventDefault();
alert(event.type);
var choice=$('input[name=choice]:checked').val();
$.ajax( {
type: "POST",
url: "submitVote.php",
data: choice,
success: function(result){
$("#testDiv").html(result);
}
});
});
HTML表单:
<form id='voteForm' action='javascript:void(0)' method='POST'><!--Changed to action='javascript:void(0)' which made it work-->
<input type='radio' name='choice' value='voteChoice1' checked='checked'>Yes<br />
<input type='radio' name='choice' value='voteChoice2'>No<br />
<input type='submit' id='submitButton' name='submitButton' value='Send'>
</form>
发布于 2014-01-23 05:41:56
根据文档:http://api.jquery.com/submit/,event.preventDefault()对提交处理程序起作用
对于"on“事件处理程序,您应该尝试使用event.stopPropagation()
虽然更好的方法是通过jquery-form插件。请参阅其online documentation中的函数"ajaxForm“。它做的正是你想要的。
发布于 2014-01-23 05:43:24
此事件绑定看起来不正确,请尝试将提交事件直接绑定到表单而不是文档:
$("#voteForm").on("submit", function(event){
event.preventDefault();
alert("event captured");
...
});
小提琴:http://jsfiddle.net/4PTdt/2/
发布于 2014-01-23 06:00:58
在函数的“和”处,只需添加以下行"return false;“。这将阻止表单提交。
https://stackoverflow.com/questions/21294502
复制相似问题