gpt4 book ai didi

javascript - Jquery 自动完成 ajax 请求仅当来自先前 ajax 请求数据的项目不匹配时

转载 作者:行者123 更新时间:2023-11-30 12:45:51 26 4
gpt4 key购买 nike

我正在使用 jQuery 自动完成功能。它在我不想要的每个按键上发出 AJAX 请求。如果来自先前 AJAX 请求的数据与搜索相匹配,则不应再发出任何 AJAX 请求。

<script>
$('#tags').autocomplete({
source: function (request, response) {
$.ajax({
url: '/TestDDl/Index',
// data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
});

在这里,如果我输入的用户名已经存在于先前的 AJAX 请求数据中,则它不应该在下一次按键时发出 AJAX 请求。

最佳答案

您可以声明一个变量,将用户输入赋给它,然后在您的成功函数中更新它。在进行下一次调用之前,检查您的变量是否与下一个数据匹配。

是这样的:

<script>
var recent = '';
$('#tags').autocomplete({
source: function (request, response) {
if (recent == request.term) {
return;
}
recent = request.term;
$.ajax({
url: '/TestDDl/Index',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.user, function (item) {
return {
label: data.name,
val: data.val
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoFocus: true,
keypress: function (event, ui) {
alert('Not Selected');
if (!ui.item) {
alert('Not Selected');
}
}
});
</script>

关于javascript - Jquery 自动完成 ajax 请求仅当来自先前 ajax 请求数据的项目不匹配时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22509408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com