代码之家  ›  专栏  ›  技术社区  ›  Chris Dutrow

jquery自动完成请求限制

  •  0
  • Chris Dutrow  · 技术社区  · 15 年前

    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 回复  |  直到 15 年前
        1
  •  0
  •   Chris Dutrow    15 年前

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

    初始化:

    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:好的部分”):

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