$(document).ready(function() { $('#domain').change(function() { // }); });
更改函数内的代码基本上会发送ajax请求来运行PHP脚本. #domain是文本输入字段.基本上我想要做的是在文本字段内的某些文本中将ajax请求作为用户类型发送(例如搜索建议).
但是,我想设置一个时间间隔,以减轻PHP服务器的负载.因为如果每当用户向文本字段添加另一个字母时jQuery发送AJAX请求,它将消耗大量带宽.
所以我想设2秒作为间隔.每次用户键入字母时都会触发AJAX请求,但最大频率为2秒.
我怎样才能做到这一点?
解决方法
你真正想要做的是检查自上次更改事件以来的时间,以便跟踪事件之间的毫秒数,而不是每2秒进行一次调用.
$(document).ready(function() { var lastreq = 0; //0 means there were never any requests sent $('#domain').change(function() { var d = new Date(); var currenttime = d.getTime(); //get the time of this change event var interval = currenttime - lastreq; //how many milliseconds since the last request if(interval >= 2000){ //more than 2 seconds lastreq = currenttime; //set lastreq for next change event //perform AJAX call } }); });