2013-04-05 149 views
1

我有一個相對簡單的jQuery AJAX調用包裝在一個函數中,我正在測試我的錯誤功能。我面臨的問題是AJAX呼叫發生得太快!這導致我的'H6'和'.loading'元素開始重複。我需要的行爲是刪除元素,然後調用ajax。jQuery AJAX觸發得太快

function getAvailability(form) { 
    var str = $(form).serialize(), 
    warning = $('#content h6'); 

    if (warning.length > 0) { 
     $(warning).remove(); 
     $('<div class="loading">Loading&hellip;</div>').insertAfter(form); 
    } 
    else 
    { 
     $('<div class="loading">Loading&hellip;</div>').insertAfter(form); 
    } 

    $.ajax({ 
     type: "POST", 
     url: "someFile", 
     data: str, 

     success: function(calendar) { 
      $('.loading').fadeOut(function() { 
       $(this).remove(); 
       $(calendar).insertAfter(form).hide().fadeIn(); 
      }); 
     }, 
     error: function() { 
      $('.loading').fadeOut(function() { 
       $('<h6>Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form); 
      }); 
     } 
    }); 

    return false; 
} 

我很想排序它就像 - >從頁面中刪除'警告',添加.loading。然後觸發AJAX。然後淡出。加載,添加&淡入警告/日曆取決於成功。


我已經修改了我的原代碼,和我有做人的功能如預期,主要是因爲我已經在阿賈克斯過程中無效的提交按鈕。

function getAvailability(form) { 
    var str = $(form).serialize(), 
    btn = $('#property_availability'); 

    // Disable submit btn, remove original 'warning', add loading spinner 
    btn.attr("disabled", "true"); 
    $('.warning').remove(); 
    $('<div class="loading">Loading&hellip;</div>').insertAfter(form); 

    $.ajax({ 
     type: "POST", 
     url: "public/ajax/returnAvailability1.php", 
     data: str, 

     success: function(calendar) { 
      $('.loading').fadeOut(function() { 
       $(this).remove(); 
       $(calendar).insertAfter(form).hide().fadeIn(); 
      }); 
     }, 
     error: function() { 
      $('.loading').fadeOut(function() { 
       $(this).remove(); 
       $('<h6 class="warning">Unfortunately there has been an error and we can not show you the availability at this time.</h6>').insertAfter(form); 
       btn.removeAttr("disabled"); 
      }); 
     } 
    }); 

    return false; 
} 

我相信,預期由於該淡出創建的時間延遲()函數的原始序列不能正常工作。

+3

你的ajax在你的當前代碼被寫入的方式被移除之前不可能啓動。如果您看到其他情況,可能是渲染問題,或者您在'ajaxSetup'的某處使用'async:false'。另外,'$(warning).remove'應該是'warning.remove' – 2013-04-05 15:12:33

+0

你可以將你的ajax包裝在'setTimeout'中,或者不要將它放在與警告刪除相同的函數中 – 2013-04-05 15:15:22

+0

另外,'if(warning.length > 0)'在這種情況下是不必要的。 – Blazemonger 2013-04-05 15:15:28

回答

2

而不是添加和刪除warning,爲什麼不顯示/隱藏利用ajaxStart和ajaxStop?

warning.ajaxStart(function() { 
    $(this).show(); 
}).ajaxStop(function() { 
    $(this).fadeOut(); 
}); 
+0

我不知道這一點。我一定會嘗試一下並回報。 – freeMagee 2013-04-06 11:47:16