我已经使用cgimail创建了一个基本的HTML联系表单,一切正常,但我无法让它在提交表单后不再重定向。我试图改为在页面顶部使用引导程序警报。
如何让表单提交,然后防止重定向?
这是代码:
<form method="post" action="/cgi-bin/cgiemail/forms/email.txt">
<fieldset>
<h2 id="contact-header">Contact</h2>
<label>Name:</label>
<input type="text" name="yourname" placeholder="" autofocus>
<label>Email Address:</label>
<input type="email" name="email" value="" placeholder="">
<label>Phone:</label>
<input type="tel" name="phone" value="" placeholder="">
<label>Message:</label>
<textarea name="message" rows="2"></textarea>
<br>
<button type="submit" id="formSubmit" class="btn">Send</button>
<input type="hidden" name="success" value="">
</fieldset>
</form>
谢谢, 莱恩
答案 0 :(得分:1)
你有两个直截了当的选择。您可以使用jQuery及其forms plugin将其转换为ajax操作,或者您可以使用自己的等效项。它看起来像这样(使用jQuery):
$('form').submit(function() {
... get all values.
... ajax post the values to the server.
return false;
});
答案 1 :(得分:1)
表单中的“action”属性告诉它将浏览器发送到该email.txt,然后可以控制是否将您重定向到另一个页面。默认情况下,它至少会将您重定向到帖子的email.txt页面,但是当发布到该页面时,cgi正在做额外的事情。
使用jQuery AJAX,您可以执行以下操作(此代码跳过错误检查):
$('form').submit(function() {
var data = { };
data.yourname = $(this).find('input[name="yourname"]').val();
data.message = $(this).find('textarea[name="message"]').val();
// do the same as above for each form field.
$.post("/cgi-bin/cgiemail/forms/email.txt", data, function() {
//add the alert to the form.
$('body').prepend('div class="alert">Success!</div>');
});
return false;
});
答案 2 :(得分:0)
如果您正在使用jQuery,那么您可以尝试取消submit
事件。首先为表单添加id
HTML:
<form id="myform" ...
JavaScript的:
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '/cgi-bin/cgiemail/forms/email.txt',
type: 'post',
data: $(this).serialize()
});
return false;
});