2011-08-10 36 views
1

我編寫了一個應用程序來向用戶詢問調查類型應用程序中的問題。 當用戶點擊答案時,AJAX(w/jQuery)會調用PHP來記錄答案,然後顯示下一個問題。這一切都很好。 問題是,我想在點擊答案後向用戶顯示一些統計信息兩秒鐘。爲此,我調用一個函數來顯示統計信息div,然後等待兩秒鐘,隱藏該div然後顯示新問題。想要讓AJAX暫停,顯示進度條2秒,然後繼續

問題是,當我使用.wnen,然後jQuery函數屏幕'凍結',所以我不能使用動畫gif讓用戶知道下一個問題即將到來。 GIF隨着屏幕的其餘部分一起凍結。

下面是我用來顯示下一個問題的功能。

有沒有更好的方法來暫停我在做什麼?

的網址是:www.imazy.com/askQuestions.php

了以下功能被稱爲像這樣:

$.ajax({ 
    type: "POST", 
    url: "recordUserAns.php", 
    data: data, 
    cache: false, 
    async: false, 

    success: function(html){ 

     showNextQn(html); 

    } 
}); 

function showNextQn($response){ 
    // -------------- Pause and fade in/out -------------- // 

    var btnVal = document.getElementById("toggleStats").innerHTML; 

    if(btnVal == "Show Stats"){ // Change the text 
     var showStats = 0; 
    }else{ 
     var showStats = 1; 
    } 

    function showDiv(){ 

     var dfd = $.Deferred(); 

     if (showStats){ 
      $('.ansPercent').fadeIn(fadeInTime, dfd.resolve); // Show the hidden div 
      // $('span#progBar').fadeIn(fadeInTime, dfd.resolve); // Show the progress bar 
     }else{ 
      $('#content').fadeOut(fadeOutTime, dfd.resolve); 
     } 
     return dfd.promise(); 
    } 

    $.when(showDiv()) 
     .then(function(ajaxResult){ 

      if (showStats){ 
       pauseScript(qnPauseTime); // Pause given # milliseconds 
      } 
      // $('span#progBar').fadeOut(0); // Hide the progress bar 
      $('#content').html($response); // Return the NEXT question 
      $('#content').fadeIn(fadeInTime); 

      // 'ajaxResult' is the server's response 
     }); 

    document.getElementById("prevBtn").style.visibility="Visible"; 

    // Remove every instance of the class, as it is no longer needed 
    $('a.ansHolder').removeClass('selected'); 
} 
+0

'async:false'會鎖定瀏覽器,所以在使用時請小心。 –

回答

1

發送Ajax請求,並確保它被髮送異步。然後,顯示進度條並啓動一個計時器(setTimeout)以開始兩秒鐘。定時器完成後,您設置一個標誌並調用「NextQuestion」過程。當ajax請求結束時,您設置另一個標誌,並再次調用NextQuestion。在NextQuestion中,檢查是否設置了兩個標誌。如果是這樣,你會顯示下一個問題。這樣,您肯定會至少等待兩秒鐘,並且在請求返回之前不會繼續,但仍然不會等待超過必要的時間。

相關問題