jQuery 是否有任何可用于请求限制的工具?类似于自动完成的工作方式。
更具体地说,这是我正在尝试做的事情:
**客户输入:** 名字:J 姓名:Smi **搜索结果:** Joe Shmoe-编辑按钮- 约翰史密斯-编辑按钮- 简·史密斯-编辑按钮- 乔·史密瑟斯-编辑按钮-
当用户在任一框中键入任何内容时,我想自己制定请求,然后 jQuery 可以决定何时以及是否发送请求,然后我将提供处理响应的代码。
jQuery 是否有任何可用于请求限制的工具?类似于自动完成的工作方式。
更具体地说,这是我正在尝试做的事情:
**客户输入:** 名字:J 姓名:Smi **搜索结果:** Joe Shmoe-编辑按钮- 约翰史密斯-编辑按钮- 简·史密斯-编辑按钮- 乔·史密瑟斯-编辑按钮-
当用户在任一框中键入任何内容时,我想自己制定请求,然后 jQuery 可以决定何时以及是否发送请求,然后我将提供处理响应的代码。
下面是我最终为限制请求编写的代码。
初始化:
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();
};
}