2012-02-22 64 views
2

語境

  • 我使用jQuery UI自動完成與遠程數據源。
  • 信息來源以這種格式發送數據:[{'label':'Bob', 'id':'03362548'}, {...}]
  • 我在搜索開始時顯示一個加載器gif。
  • 數據過濾在服務器端完成。
  • 如果沒有結果,我想隱藏加載程序gif(服務器發送[])。

問題

如何檢測如果搜索沒有結果隱藏裝載機GIF?自動完成:檢測沒有結果與遠程數據源

代碼

$('#redir-output').autocomplete({ 
    source: 'php/ajax/autocomplete.php', 
    search: function(event, ui) { 
     $('#redir-loader').show(); 
    }, 
    open: function(event, ui) { 
     $('#redir-loader').hide(); 
    }, 
    select: function(event, ui) { 
     $(this).attr('name', ui.item.id); 
    } 
}); 

回答

1

默認情況下,當插件顯示的結果,它會檢查是否存在的數據顯示。如果沒有,則關閉菜單。

_response: function(content) { 
    if (!this.options.disabled && content && content.length) { 
     ... 
    } else { 
     // it closes the menu when content.length == 0 (no data) 
     this.close(); 
    }​ 

關閉菜單引發了「關閉」事件,所以我儘管你可以使用它。然而,這只是觸發關閉事件時,菜單可見:

close: function(event) { 
    clearTimeout(this.closing); 
    // as the menu might not be visible at that moment, this is reliable 
    if (this.menu.element.is(":visible")) { 
     ... 
     this._trigger("close", event); 
    } 
}​ 

我認爲你將不得不使用源作爲回調並實現自己的Ajax請求。使用「完整」回調,您可以隱藏加載圖標,在請求結束時,無論如何都應該隱藏,數據返回與否:

$('#redir-output').autocomplete({ 
    source: function(request, response) { 

     $.ajax({ 
      url: 'php/ajax/autocomplete.php', 
      data: request, 
      dataType: "json", 
      success: function(data, status) { 
       response(data); 
      }, 
      error: function() { 
       response([]); 
      }, 
      complete: function() { 
       $('#redir-loader').hide(); 
      } 
     }); 

    }, 

    , 
    search: function(event, ui) { 
     $('#redir-loader').show(); 
    }, 
    open: function(event, ui) { 
     $('#redir-loader').hide(); 
    }, 
    select: function(event, ui) { 
     $(this).attr('name', ui.item.id); 
    } 
});? 
+0

好,它的工作原理。我只是做'成功:函數(數據,狀態){$('#redir-loader')。hide();響應(數據); }',沒有'error'和'complete'。謝謝。 – 2012-02-22 14:19:25

+0

我認爲你完全可以依靠ajax回調:「beforeSend」顯示加載器,「完成」隱藏。然後,您可以從自動填充中移除「搜索」和「打開」事件。 – 2012-02-22 14:20:45

+0

我知道了,謝謝。 :) – 2012-02-22 14:26:02