2011-02-17 113 views
0

我在項目中使用jQuery BlockUI。對於特定的用戶操作,我想阻止UI,然後將數據發送到服務器。當發生超時事件或服務器返回時,我想取消阻止頁面。jQuery blockUI和AJAX POST

我似乎無法實現此行爲。這是我到目前爲止(不工作)

$(document).ready(function(){ 
    $('#test').click(function(event){ 
     $.blockUI({ message: $('#mydiv') }); 

     $.ajax({ 
       type: 'POST', 
       url: 'www.example.com', 
       data: somedata, 
       dataType: "json" 
     }); 

     setTimeout(function() { 
       $.unblockUI({ 
        onUnblock: function(){ 
         alert('onUnblock'); 
        } 
       }); 
      }, 2000); 
}); 

任何人都可以發現我可能做錯了什麼?

+0

我認爲你會阻止你的用戶界面,但它永遠不會暢通無阻? – Tx3 2011-02-17 07:37:21

回答

4

我想你需要爲此設置ajax自己的成功,錯誤和超時屬性。忘記使用其他setTimeout。

這裏是文檔。

http://api.jquery.com/jQuery.ajax/

更像:

$.ajax({ 
       type: 'POST', 
       url: 'www.example.com', 
       data: somedata, 
       dataType: "json", 
       timeout: /*your time*/, 
       success: function(result){ /*unblock*/ }, 
       error: function (xhr, ajaxOptions, thrownError){ /*unblock*/ } 
     }); 
0

使用完整的回調

$.ajax({ 
      type: 'POST', 
      url: 'www.example.com', 
      data: somedata, 
      dataType: "json", 
      complete: function(){ 
      // unblock stuff here 
      } 
    }); 

成功和完整的區別在於,完全就是所謂的Ajax調用是否成功。如果您只使用成功,那麼如果AJAX呼叫失敗,UI將保持阻塞狀態。

+0

您也可以添加`timeout`屬性。 – Don 2011-02-17 07:45:11