我有下一个代码并且效果很好,问题是当用户完成单词编写时,脚本会不断创建帖子调用并不断更改建议列表。
我想做一些事情,如果用户继续写一个单词,脚本会停止所有的帖子调用,只做最后一次。
$("#inputString").keydown(function() {
lookup($(this).val());
//alert('a');
});
function lookup(inputString) {
if(inputString.length == 0) {
$('#suggestions').fadeOut(); // Hide the suggestions box
} else {
$.post("../jsonshow.php", {q: ""+inputString+""}, function(data) { // Do an AJAX call
$('#suggestions').fadeIn(); // Show the suggestions box
$('#suggestions').html(data); // Fill the suggestions box
});
}
}
答案 0 :(得分:1)
您可以使用$.ajax
代替$.post
并中止previous requests
并仅发送current Request
..
这种东西..
$("#inputString").keydown(function() {
lookup($(this).val());
//alert('a');
});
var ajaxRequests;
function lookup(inputString) {
if (inputString.length == 0) {
$('#suggestions').fadeOut(); // Hide the suggestions box
}
else {
var ajaxReq =
$.ajax({
type: "POST",
url: "../jsonshow.php",
data: "" + inputString + "",
dataType: 'html',
beforeSend: function() {
var req = ajaxRequests;
if (req != null && req != undefined) {
req.abort();
// Abort the previous requests
}
},
success: function(data) {
$('#suggestions').html(data).fadeIn();
// Fill the suggestions box
},
complete : function(){
ajaxrequests = null;
}
});
ajaxRequests = ajaxReq;
}
}
答案 1 :(得分:-1)
只有在用户点击空间时调用ajax怎么样?
$("#inputString").keydown(function(e) {
if(e.keyCode == 32) lookup($(this).val());
});