javascript - 在同一页面上提交具有已发送状态的联系表
问题描述
我正在建立一个投资组合网站,在联系表格中,我希望在提交后获得成功/失败响应。在此过程中,我更愿意保持在同一页面上。
我尝试了与该主题相关的其他页面中的其他解决方案,但我不明白为什么它们对我不起作用。由于我是新手,我将不胜感激一个清晰的解释。非常感谢!
我尝试了此主题下的解决方案:在同一页面上提交带有成功/失败警报的联系表
我当前的 HTML 代码是;
<form id="contact-form" method="post" action="contact.php" role="form" enctype="text/plain">
<div class="messages"></div>
<div class="controls">
<div class="form-group">
<input id="form_name" type="text" name="name" class="form-control" placeholder="Name *" required="required" data-error="name is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_email" type="email" name="email" class="form-control" placeholder="E-mail *" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input id="form_subject" type="text" name="subject" class="form-control" placeholder="Subject">
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="send a message."></textarea>
<div class="help-block with-errors"></div>
</div>
<input type="submit" name="submit" class="btn btn-send float-" value="Send message">
<p class="text-muted"><strong>*</strong> These fields are required.</p>
</div>
<div class="clearfix"></div>
</form>
我希望在提交表单后在同一页面上看到确认或失败报告。它可以在页面上的任何位置。我只是想让访问者知道我收到了他们的消息或没有。
解决方案
简单示例 jQuery 版本:
$("#contact-form").submit(function() {
var name = $("#form_name").val();
var email = $("#form_email").val();
// ...other fields
// and validation if empty or e-mail is valid etc.
// if validation fails just return false;
if( !name ) {
// here You can send message or activate help-block
return false;
}
// if everything correct use for example ajax from jquery
$.ajax({
url: '/url/to/receiver',
type: 'post',
data: { name: name, .... },
dataType: 'jsonp',
success: function( r ) {
if( r.success ) {
// message and pass form validation
// clear fields, or hide contact form
}
if( r.error ) {
// show error
}
}
});
return false;
});
请记住从服务器 JSON 返回,例如 { success: true } 或 { error: true, msg: "message why failed" }。
但它会好得多,当你将输入类型=提交到按钮,然后使:
$("#contact-form .class-of-input-button").off().on('click', function() { /* rest of the code */ });
推荐阅读
- c# - 通过 user32.dll 在 Listbox 中选择 CheckBoxes?(
- c++ - OpenGL:将动态分配的矩阵传递给统一
- stripe-payments - Stripe 通过格子验证收集经常性 ACH 付款
- android - 在 InstrumentedTest 上使用 SSL 和 MockWebServer
- oop - 抽象数据类型与非抽象数据类型(Java 中)
- javascript - Ajax 调用加载的 Javascript 不执行?
- java - 奇怪的Java并发修改异常示例
- ios - 如何在 Swift 中组合 2 个 CoreData 谓词?
- c# - 筛选 2 个条件,包括不使用 Microsoft Graph SDK 的日期
- java - 从 firebase 获取数据为空