2015-12-30 33 views
0

我正在使用jquery倒數計時器插件(http://keith-wood.name/countdown.html)來顯示時間。我正在調用一個函數來在回調事件'onTick'上添加更多時間。當時間倒計時到00:00:00時,該函數將進行ajax調用以增加額外的時間。它工作正常,但每次計時器等於00時,ajax都會進行多次調用(> 15)。我怎樣才能讓它發送一個電話?我試着做異步:假,但它仍然是多次調用。謝謝。如何阻止AJAX進行多個呼叫?

$(this).countdown({ until: time, format: 'HMS', onTick: addExtraTime }); 

function addExtraTime() {  
if ($.countdown.periodsToSeconds(periods) === 00) { 
      var postValue = { ID: id } 
      if (!ajaxLoading) { 
       ajaxLoading = true; 
       $.ajax({ 
        url: "@Url.Action("AddExtraTime", "Home")", 
        type: 'post', 
       dataType: 'json', 
       contentType: "application/json", 
       data: JSON.stringify(postValue), 
       success: function() { 
        // show success 
       }, 
       error: function(data) { 
        // show error 
       } 
      }); 
      ajaxLoading = false; 
     } 
     } 
    } 

回答

2

你設置ajaxLoading = false; Ajax請求仍然是正在做,即使,它設置爲false請求完成

 if (!ajaxLoading) { 
      ajaxLoading = true; 
      $.ajax({ 
       url: "@Url.Action("AddExtraTime", "Home")", 
       type: 'post', 
      dataType: 'json', 
      contentType: "application/json", 
      data: JSON.stringify(postValue), 
      success: function() { 
       // show success 
      }, 
      error: function(data) { 
       // show error 
      } 
      complete: function(){ 
       ajaxLoading = false; 
      } 
     }); 
     //ajaxLoading = false; 
    } 
4

你有一個變量,ajaxLoading,你用它來確定是否一個Ajax請求是在飛行,但你把它調用$.ajax(),而不是當你得到迴應後,設置爲false立即。將它設置爲false而不是您的成功和錯誤處理程序。