如何解决如何在不离开页面的情况下使用 AJAX 提交表单 HTML Formsubmit
我正在使用 Formsubmit 将联系我们表单发送到我的电子邮件,到目前为止它正在工作。
但是我希望当用户发送表单时它不会将其重定向到源 thank you page 而是我只想在同一页面上显示感谢文本。我想用我自己的。
所以我跟着 documentation 我想出了以下内容: 不幸的是,当我尝试验证表单按钮时,它不起作用
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->
<script type="text/javascript">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),method: "POST",url: "https://formsubmit.co/el/vupawa",dataType: 'html',accepts: 'application/json',data: frm.serialize(),success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},error: function (response) {
console.log('An error occurred.');
console.log(response);
}
complete: function(response){
setTimeout(ajax,1000);
}
});
});
});
</script>
注意:取消注释这一行 <input type="hidden" name="_next" value="thanks.html">
将验证表单并通过另一个页面,这不是我在这里想要的。
有什么想法吗?
解决方法
为了防止提交你应该在
中返回falsefrm.submit(function (e) {
return false;
})
或者在表单标签中
<form onSubmit="return false">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),method: "POST",url: "https://formsubmit.co/el/vupawa",dataType: 'html',accepts: 'application/json',data: frm.serialize(),success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},error: function (data) {
console.log('An error occurred.');
console.log(data);
}
});
return false; // here a change
});
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。