2012-02-07 25 views
0

我使用jQuery UI自动完成和来自远程数据源的数据。我使用的情况是真的相似,这里的例子:jQuery UI-如何防止自动完成菜单在击键之间暂时消失?

http://jqueryui.com/demos/autocomplete/#remote

唯一的区别是,我把我的延迟为0。在按键之间,菜单消失一秒钟〜100milli的约1/10显示更新的自动完成列表之前的秒数。

有没有反正我可以防止菜单之间的击键之间暂时消失?一个好的用例是谷歌的搜索,在击键之间,建议框不会暂时消失。

回答

2

IMO,使用远程数据源时,设置延迟零不是一个好习惯。它会发送比需要更多的请求,并为服务器收取额外费用。

无论如何,我认为你可以通过自己定义source选项作为回调来达到你想要的效果。

首先有点解释。我想你正在使用传递url的远程功能作为插件的源代码。该插件实际上包装此为实现这样的回调:

// in case the option "source" is a string 
url = this.options.source; 
this.source = function(request, response) { 
    if (self.xhr) { 
     self.xhr.abort(); 
    } 
    self.xhr = $.ajax({ 
     url: url, 
     data: request, 
     dataType: "json", 
     autocompleteRequest: ++requestIndex, 
     success: function(data, status) { 
      if (this.autocompleteRequest === requestIndex) { 
       response(data); 
      } 
     }, 
     error: function() { 
      if (this.autocompleteRequest === requestIndex) { 
       response([]); 
      } 
     } 
    }); 
}; 

正如你所看到的,如果已经有一个Ajax请求回事,它abords它。这种情况在你的情况下作为请求,与你的服务器一样快,需要一些时间,你的延迟为零。

if (self.xhr) { 
    self.xhr.abort(); 
} 

这将真正执行,将执行本身带有空数据集response回调中止请求的错误回调。如果你看一下响应回调,关闭菜单,如果数据为空:

_response: function(content) { 
    if (!this.options.disabled && content && content.length) { 
     ... 
    } else { 
     this.close(); 
    } 

实际上,你可以定义自己的source回调,使您的Ajax请求自己和不放弃任何挂起的更改的默认行为请求。例如:

$('#autocomplete').autocomplete({ 
    source: function(request, response) { 
     $.ajax({ 
      url: url, 
      data: request, 
      dataType: "json", 
      success: function(data, status) { 
       // display menu with received dataset 
       response(data); 
      }, 
      error: function() { 
       // close the menu on error by executing the response 
       // callback with an empty dataset 
       response([]); 
      } 
     }); 
    } 
});