event.preventDefault();不工作
问题描述:
我正在尝试提交表单而不刷新页面,但是event.preventDefault();
无法正常工作.到目前为止,这就是我所拥有的
I'm trying to submit a form without refreshing the page, but event.preventDefault();
isn't working. Here's what I have thus far
$('#contactform').on('submit', function() {
event.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
succss: function(response) {
console.log(response);
}
});
});
但是,一旦按下提交按钮,页面仍然会重新加载.有什么建议吗?
But the page still re-loads once the submit button has been pressed. Any suggestions?
更新:主表单页面的代码如下;
Update: The code for the main form page is as follows;
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="<?php echo get_template_directory_uri();?>/ajax/main.js"></script>
<form action="<?php echo get_template_directory_uri(); ?>/ajax/contact.php" method="post" id="contactform">
<input type="text" name="fname" placeholder="Name" />
<input type="email" name="email" placeholder="Email" />
<textarea name="message" id="" cols="30" rows="10" placeholder="Your Message"></textarea>
<input type="submit" name="Submit" />
</form>
答
您需要将事件作为第一个参数传递给函数.
You need to pass the event to the function as the first parameter.
$('#contactform').on('submit', function(event) {
event.preventDefault();
...
如果这不起作用,则可能还有其他问题.您需要通过将侦听器包装在.ready()
:
If that doesn't work, you may have an additional problem. You need to make sure the DOM is ready before binding anything to the form by wrapping your listener in a .ready()
:
$(document).ready(function() {
$('#contactform').on('submit', function(event) {
event.preventDefault();
...