[英]Stop Ajax Request And Call New Ajax
in this code, i take typing character from user and search it in database,but when user enter each character,running new ajax request with previous ajax, 在这段代码中,我从用户那里键入字符并在数据库中进行搜索,但是当用户输入每个字符时,使用先前的ajax运行新的ajax请求,
i want when call search function, cancel previous ajax request and run new ajax request; 我想在调用搜索功能时,取消先前的ajax请求并运行新的ajax请求;
html code : html代码:
<input type="text" onkeyup="search()">
js code: js代码:
function search () {
var request=$.ajax({
type: "POST",
url: "php/h.php",
data: {k_word:k_word},
dataType: "json",
success: function (data) {
ghtml(data)
}
})
}
Also i tried with abrot() like this : 我也尝试了abrot()这样的:
var request;
function search () {
request.abort();
request=$.ajax({
type: "POST",
url: "php/h.php",
data: {k_word:k_word},
dataType: "json",
success: function (data) {
ghtml(data)
}
})
}
but not working 但不起作用
That's generally not how it's done, instead throttling is used to only call the ajax function when the user stops typing for a given time 通常这不是完成操作的方式,而是仅在用户在给定时间内停止键入时才使用节流功能来调用ajax函数
First of all, get rid of the inline javascript 首先,摆脱内联javascript
<input type="text" id="myInput" />
then use an event handler 然后使用事件处理程序
$('#myInput').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
$.ajax({
type : "POST",
url : "php/h.php",
data : {k_word:k_word},
dataType : "json",
success : function (data) {
ghtml(data)
}
});
}, 500)
);
});
This sets a timeout on the ajax call, and that timeout is cleared if a new key is pressed within half a second, so the ajax call is only made when the user stops typing for more than 500 milliseconds 这将设置ajax调用的超时,并且如果在半秒钟内按下新键,则超时将被清除,因此仅当用户停止键入超过500毫秒时才进行ajax调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.