我浏览了所有类似的帖子,但似乎无济于事。这就是我所拥有的
<section> <form id="contact-form" action="" method="post"> <fieldset> <input id="name" name="name" placeholder="Name" type="text" /> <input id="email" name="email" placeholder="Email" type="text" /> <textarea id="comments" name="comments" placeholder="Message"></textarea> <div class="12u"> <a href="#" id="form-button-submit " class="button" onClick="sendForm()">Send Message</a> <a href="#" id="form-button-clear" class="button" onClick="document.getElementById('contact-form').reset()">Clear Form</a> </div> <ul id="response"></ul> </fieldset> </form> </section>
function sendForm() { var name = $('input#name').val(); var email = $('input#email').val(); var comments = $('textarea#comments').val(); var formData = 'name=' + name + '&email=' + email + '&comments=' + comments; $.ajax({ type: 'post', url: 'js/sendEmail.php', data: formData, success: function(results) { $('ul#response').html(results); } }); // end ajax }
我无法做的是防止在按时刷新页面#form-button-submit。我尽力return false;尝试了preventDefault()每一个组合,包括return false;内部onClick。我也尝试使用input type="button"和type="submit"相反的相同结果。我无法解决这个问题,这真是疯了。由于某些设计原因,我尽可能使用超链接。非常感谢您的帮助。
#form-button-submit
return false;
preventDefault()
onClick
input type="button"
type="submit"
像这样修改函数:
function sendForm(e){ e.preventDefault(); }
正如评论所提到的,通过事件:
onclick = sendForm(event);
更新2:
$('#form-button-submit').on('click', function(e){ e.preventDefault(); var name = $('input#name').val(), email = $('input#email').val(), comments = $('textarea#comments').val(), formData = 'name=' + name + '&email=' + email + '&comments=' + comments; $.ajax({ type: 'post', url: 'js/sendEmail.php', data: formData, success: function(results) { $('ul#response').html(results); } }); });