Javascript 如何在angularjs中只发送一个请求而不是多个请求?
我有一个演示,在这个演示中,用户在输入字段中键入任何内容,然后请求进入服务器。当前,只要用户键入它,就会触发请求我只需要发出一个请求。例如,如果我键入Javascript 如何在angularjs中只发送一个请求而不是多个请求?,javascript,angularjs,Javascript,Angularjs,我有一个演示,在这个演示中,用户在输入字段中键入任何内容,然后请求进入服务器。当前,只要用户键入它,就会触发请求我只需要发出一个请求。例如,如果我键入“abc”它将发出三个请求。此用户是否可能键入任何不带停止的内容,停止一秒后,我将发出请求 我知道,输入可以通过ng model options指令解除公告:但它会在给定时间后触发,但我希望用户类型只要不停止,但在停止后触发请求 这是我的密码: 使用setTimeout/clearTimeout实现您自己的去抖动,类似这样的操作可以: app.c
“abc”
它将发出三个请求。此用户是否可能键入任何不带停止的内容,停止一秒后,我将发出请求
我知道,输入可以通过ng model options指令解除公告:但它会在给定时间后触发,但我希望用户类型只要不停止,但在停止后触发请求
这是我的密码:
使用
setTimeout
/clearTimeout
实现您自己的去抖动,类似这样的操作可以:
app.controller('MainCtrl', function($scope,$http) {
$scope.name = 'World';
var timeout = null; // the timeout handle
$scope.keyupevt = function() {
clearTimeout(timeout); // clear any previous timeout (if null, nothing will happen)
timeout = setTimeout(function() { // set a new timeout
console.log('xx'); // that will make the request after 1 second
$http.get("data.json")
.then(function(response) {
console.log(response);
});
timeout = null; // reset timeout (not really necessary but it won't do any harm)
}, 1000); // the code inside will be called after exactly 1000 ms
}
});
每次按键按下时,一个请求将被设置为在该按键按下事件发生1秒后发生。如果之前的请求尚未发生,则该请求将被取消,并将在1秒后设置为发生新的请求。etc如果您失去焦点并输入>0,可能会触发它。您还可以有一个最小字符限制,并在发送请求之前等待至少达到该限制。
app.controller('MainCtrl', function($scope,$http) {
$scope.name = 'World';
var timeout = null; // the timeout handle
$scope.keyupevt = function() {
clearTimeout(timeout); // clear any previous timeout (if null, nothing will happen)
timeout = setTimeout(function() { // set a new timeout
console.log('xx'); // that will make the request after 1 second
$http.get("data.json")
.then(function(response) {
console.log(response);
});
timeout = null; // reset timeout (not really necessary but it won't do any harm)
}, 1000); // the code inside will be called after exactly 1000 ms
}
});