jQuery自动完成请求限制

时间:2010-10-18 20:53:48

标签: jquery autocomplete autosuggest

jQuery是否有任何可用于请求限制的工具?类似于自动完成的方式。

更具体地说,这是我正在尝试做的事情:

    **Customer entry:**
    First Name: J
    Last Name:  Smi

    **Search results:**
    Joe Shmoe     -edit button-
    John Smith    -edit button-
    Jane Smith    -edit button-
    Joe Smithers  -edit button-

当用户在任一框中键入任何内容时,我想自己制定请求,然后jQuery可以决定何时以及是否发送请求,然后我将提供处理响应的代码。

1 个答案:

答案 0 :(得分:0)

以下是我为限制请求而编写的代码。

<强>初始化:

var global = {};
global.searchThrottle = Object.create(requestThrottle);

<强>用法:

this.searchThrottle.add(function(){
         //Do some search or whatever you want to throttle 
 });

源代码:

// runs only the most recent function added in the last 400 milliseconds, others are 
// discarded
var requestThrottle = {};

// Data
requestThrottle.delay = 400; // delay in miliseconds

requestThrottle.add = function(newRequest){
 this.nextRequest = newRequest;
 if( !this.pending ){
  this.pending = true;
  var that = this;
  setTimeout( function(){that.doRequest();}, this.delay);
 }
}

requestThrottle.doRequest = function(){
 var toDoRequest = this.nextRequest;
 this.nextRequest = null;
 this.pending = false;
 toDoRequest();
}

Object.create()源代码(取自“Javascript:The Good Parts”):

if( typeof Object.create !== 'function'){
 Object.create = function(o){
  var F = function(){};
  F.prototype = o;
  return new F();
 };
}