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,
i want when call search function, cancel previous ajax request and run new ajax request;
html code :
<input type="text" onkeyup="search()">
js code:
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 :
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
First of all, get rid of the inline 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.