我正在尝试提交表单而不刷新页面,但是event.preventDefault();无法正常工作.这是我到目前为止所拥有的
$('#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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
但是,一旦按下提交按钮,页面仍会重新加载.有什么建议?
更新:主表单页面的代码如下;
<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>
Run Code Online (Sandbox Code Playgroud)
nul*_*ity 12
您需要将事件作为第一个参数传递给函数.
$('#contactform').on('submit', function(event) {
event.preventDefault();
...
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,您可能还有其他问题.通过将侦听器包装在以下内容中,您需要确保DOM已准备就绪,然后才能将任何内容绑定到表单.ready():
$(document).ready(function() {
$('#contactform').on('submit', function(event) {
event.preventDefault();
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9401 次 |
| 最近记录: |