jQuery自动完成请求限制 [英] jQuery auto complete request throttling

查看:136
本文介绍了jQuery自动完成请求限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does jQuery have any tools I can use for request-throttling? Something similar to how auto complete works.

更具体地说,这是我想要做的事情:

More specifically this is the kind of thing I'm trying to do:


    **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可以决定何时以及是否发送请求,然后我会提供用于处理响应的代码。

When a user types a anything in either of the boxes, I'd like to formulate the request myself, and then jQuery can decide when and if to send the request, and then I would provide the code for handling the response.

推荐答案

以下是我最后编写的用于限制请求的代码。

Below is the code I ended up writing for throttling requests.

初始化:

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):

Object.create() source code (taken from "Javascript: The Good Parts"):

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

这篇关于jQuery自动完成请求限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆