[英]Contact form using e.preventDefault(); not working live
UPDATE-在此URL上找到联系表格。
我正在尝试使用本教程使以下联系表起作用。
我设法使用apache网络服务器使一切正常工作在我的计算机上。 将文件上传到在线网站后,ajax函数无法启动。我好像是e.preventDefault();
上载后停止工作,并且表单被重定向到新站点,而不仅仅是在不重新加载的情况下在站点上进行处理。
我也一直在尝试使用return false;
而不是e.preventDefault();
没有任何成功。
她是我的代码:
html的
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
.js文件
$(function(){
$('form').submit(function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading").fadeOut(function(){
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
})
请帮忙!
那是因为您的JS缺少结尾});
。 请检查此演示以确认确实阻止了默认操作并且ajax确实启动了。但是,我期待着POST
但是却看到了OPTIONS
请求。
注意 :为元素提供name
或id
属性值submit
是不好的做法。 例如,您不能使用JavaScript通过默认表单提交来提交表单this.submit() or $('form')[0].submit()
不会出现错误...submit() is not a function ....
$(function() { $('form').submit(function(e) { var thisForm = $(this); //Prevent the default form action //return false; e.preventDefault(); //Hide the form $(this).fadeOut(function() { //Display the "loading" message $("#loading").fadeIn(function() { //Post the form to the send script $.ajax({ type: 'POST', url: thisForm.attr("action"), data: thisForm.serialize(), //Wait for a successful response success: function(data) { //Hide the "loading" message $("#loading").fadeOut(function() { //Display the "success" message $("#success").text(data).fadeIn(); }); } }); }); }); }); }); // <==== MISSING THIS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form method="post" action='mail/mail.php'> <label>Name</label> <input name="name" id="name" placeholder="Name.." required="true" class="input-field"> <label>Mail</label> <input type="email" name="email" placeholder="Mail.." required="true" class="input-field"> <label>Msg</label> <textarea name="message" id="message" class="textarea-field" required="true"></textarea> <input type="submit" id="submit" name="submit" value="Send"> </form> <div id="loading"> Sender melding... </div> <div id="success"> </div>
由于无论如何都是通过AJAX提交的,因此您可能会发现将输入类型更改为button并绑定为click而不是表单提交更容易,从而避免了您试图绕过的默认提交行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.