我有一个脚本
$('#postinput').on('keyup',function(){
var txt=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt='+txt,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
Run Code Online (Sandbox Code Playgroud)
假设有人输入 a ,ajax run 。他立即输入 bc 等等。Ajax 每次都会运行。有没有办法在发出新请求时停止以前的请求?
您可以使用abort()的方法xhr。尝试这个:
var currentXhr;
$('#postinput').on('keyup',function(){
currentXhr && currentXhr.readyState != 4 && currentXhr.abort(); // clear previous request
var txt = $(this).val();
var currentXhr = $.ajax({
type: "POST",
url: "action.php",
data: 'txt=' + txt,
cache: false,
context:this,
success: function(html) {
alert(html);
}
});
});
Run Code Online (Sandbox Code Playgroud)
如果您不想使用全局变量,可以将其存储xhr在元素data-*的属性中#postinput。
另一种方法是仅在用户停止输入时触发 AJAX 请求:
var timer;
$('#postinput').on('keyup',function(){
clearTimeout(timer);
var txt = $(this).val();
var timer = setTimeout(function() {
$.ajax({
type: "POST",
url: "action.php",
data: 'txt=' + txt,
cache: false,
context:this,
success: function(html) {
alert(html);
}
});
}, 100); // sends request 100ms after typing stops.
});
Run Code Online (Sandbox Code Playgroud)