2014-12-21 27 views
0

我有一個由jQuery提交的表單有一個錯誤驗證服務器端的ajax。在beforeSend上,我顯示了 一個gif加載器和一些加載文本,並且當成功方法發送驗證時,我會顯示相應的錯誤消息。 此消息在x秒後有超時隱藏。無論如何,當我繼續點擊提交按鈕,0​​setTimeout自己混淆,以前的不清除。這裏是我使用的代碼:ajax成功jQuery clearTimeout越來越困惑,並沒有清除以前的超時

編輯

$('form').on('submit', function(e) { 

e.preventDefault(); 
var timer = null; 

$.ajax({ 
    beforeSend; function() { 
     $('.response').html('Processing form, please wait...'); 
    }, 

    success: function(data) { 

     if(data.error == true) { 
      $('.response').html('An error occurred.'); 
     } else { 
      $('.response').html('Thank you. Form submitted successfully.'); 
     } 

     if(timer) { clearTimeout(timer) }; 
     timer = setTimeout(function() { 
      $('.response').html('* Indicates required fields.'); 
     }, 10000); 

    } 
}); 
}); 

知道的任何建議。

回答

2

timer變量的作用域是你的success功能,所以它總是null當達到你的代碼,以清除舊超時。將timer的聲明移到您的AJAX調用之外,並且它應該可以工作。

var timer = null; 

$.ajax({ 
    beforeSend: function() { ... }, 
    success: function(data) { 
     if(timer) { clearTimeout(timer) }; 
     timer = setTimeout(myfunction, 10000); 
    } 
}); 
+0

是的,我也試過,但結果仍然一樣。 – user558134

+0

@ user558134如果這不起作用,您將不得不提供更多的代碼,因爲如果沒有它,我們沒有足夠的上下文來了解錯誤。 –

+0

好吧,我發佈了一些更多的代碼。這是非常多的。 – user558134