如果用户未正确填写所有字段,则会显示包含所有错误的错误块。目前,如果他们再次单击“提交”,则当小型加载器旋转并再次提交表单时,错误消息将保留在那里。我试图隐藏错误消息,但它甚至在初始提交时隐藏了消息,这是不对的。它只需要隐藏错误消息,如果它是可见的。
$.ajax({
type: "POST",
url: "process.php",
data: str,
beforeSend: function() {
$("#contact-submit").hide();
$("#loading").show();
},
success: function(response) {
$('#error').html(response);
if (!response || response.length == 0 || response.indexOf("Your message was sent") >= 0)
$("#contact-form").hide();
$("#contact-submit").show();
$("#loading").hide();
这是我的新解决方案:
$.ajax({
type: "POST",
url: "process.php",
data: str,
beforeSend: function() {
$("#contact-submit").hide();
$("#loading").show();
},
success: function(response) {
$('#error').html(response);
if (!response || response.length == 0 || response.indexOf("Your message was sent") >= 0)
$("#hfarm-contact-form").hide();
$("#contact-submit").show();
$("#loading").hide();
$('#error').fadeIn().html(response);
setTimeout(function(){
$('#error').fadeOut("Slow");
}, 5000);
答案 0 :(得分:0)
您可以使用jQuery data存储与contact-submit元素相关联的变量:
此外,您可以使用
complete: function(jqXHR, textStatus ) {
重置显示和隐藏元素等值以及此新变量的值。
延迟功能仅用于片段目的,以减慢执行速度。 我的片段:
function delay(ms) {
var cur_d = new Date();
var cur_ticks = cur_d.getTime();
var ms_passed = 0;
while(ms_passed < ms) {
var d = new Date(); // Possible memory leak?
var ticks = d.getTime();
ms_passed = ticks - cur_ticks;
// d = null; // Prevent memory leak?
}
}
$(function () {
// Initialize....
$("#loading").hide();
$('#contact-submit').data('isInprogress', false);
// on input submit click....
$('#contact-submit').on('click', function(e) {
e.preventDefault();
// before to start anything: check form and if error
// stop (return immediately).
// you cannot stop the submit inside the ajax call.
// do your control here.....
// after continue..... taking in account an ajax call is asyncronous
var isInprogress = $('#contact-submit').data('isInprogress');
if(isInprogress === true) {
alert('Already loading...');
return;
}
$('#contact-submit').data('isInprogress', true);
var str = '';
$.ajax({
dataType: 'json',
url: 'https://api.github.com/users',
data: str,
beforeSend: function() {
$("#contact-submit").hide();
$("#loading").show();
},
success: function(data, jqXHR ) {
var a = data;
},
complete: function(jqXHR, textStatus ) {
delay(2000);
$('#contact-submit').data('isInprogress', false);
$("#contact-submit").show();
$("#loading").hide();
}
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loading">loading.......</div>
<form id="frm">
<input id="contact-submit" type="submit" value="Click Me To get Data with Ajax">
</form>
&#13;