我试图在CMS页面内提交表单,并且不希望在处理php邮件脚本后加载新页面。相反,我需要显示一行成功消息(而不是一个警告弹出框),而无需重新加载页面或转到另一个页面。
这是我的代码,我的理解是event.preventDefault
应该允许留在同一页面上,$("#contactResponse").html(data);
应该把成功消息放在同一页面上。
这是我的div标签上面的形式应该收到成功消息(我也试过把它放在我的形式之后):
<div id="contactResponse"></div>
这是我的表单标签:
编辑:包括我的表单代码以及:(div类的东西是从一个自定义的css,别人已经做了)
<form id="contactForm" name="contactForm" method="post" action="/myemail.php">
<div class="form-group"><input class="form-control" name="email" type="email" placeholder="Email Address" /></div>
</div>
<div class="col-sm-4">
<div class="form-group"><input class="form-control" name="question" type="text" placeholder="What is your question?" /></div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" type="submit" value="Request Information"></div>
</form>
这是我的表单和div标签上面的脚本:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$("#contactForm").submit(function(event) {
event.preventDefault();
var $form = $(this),
$submit = $form.find('button[type="submit"]'),
email_value = $form.find('input[name="email"]').val(),
message_value = $form.find('input[name="question"]').val(),
url = $form.attr('action');
var posting = $.post(url, {
email: email_value,
question: message_value
});
posting.done(function(data) {
$("#contactResponse").html(data);
});
});
</script>
邮件工作,但php脚本是在服务器上,它带我到一个不同的页面。
有人能给我一些建议吗?
谢谢
试试这个,它对我有用
<script>
// Get the form.
var form = $('#contactForm');
// Get the messages div.
var formMessages = $('#contactResponse');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
// $('#subject').val('');
// $('#company').val('');
$('#message').val('');
$(form).hide();
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$( "#contact" ).children(".loading").remove();
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
</script>