gpt4 book ai didi

jquery - 如何为 ajax 请求添加延迟以避免性能问题

转载 作者:行者123 更新时间:2023-12-01 05:32:30 28 4
gpt4 key购买 nike

我有一个函数,可以在输入时返回 AJAX 中触发的一定量的数据。每次它都会去 Oracle DB 获取数据并显示输出。

但是,一旦我输入像“你好,我的名字是”这样的“长”字符串,每次我输入一个键时,它都会启动一个请求(一次 10 个请求),并且需要 5 秒才能获得 1请求响应。

这导致我的应用程序出现性能问题。请问我该如何避免这种情况?

我已经尝试过动态和延迟,但不起作用。我正在使用 typeahead 2 (typeahead-bs2.min.js)。

$( "#customer_description" ).typeahead({

dynamic: true,
delay: 5000,
source: function (query, process) {
$.ajax({
url: '/data/customer.php',
type: 'POST',
dataType: 'JSON',
//contentType: "text/json; charset=utf-8",
data: {
all: query,
},
success: function(data) {
//console.log(data);
process(data);
}
});
}
});

最佳答案

一旦用户停止输入并检查输入长度,您可以在 1.5/2 秒间隔后触发请求,如 Sami 所建议的那样。 .

除此之外,为了避免发送多个请求,您可以随时中止前一个请求并发送新请求。

 var start = new Date()
,end, request;

$('input:text').on('change', function(){
end = new Date();
var input = $(this).val();
var diff = (end - start)/1000;

//checking for a 1.5 sec delay and input length
//You can adjust the delay time, I have kept it as 1.5seconds
if(diff > 1.5 && input.length > 5){
if (request !== undefined){
//aborting the previous request
request.abort();
}
start = new Date();

//storing the ajax request in a variable so that it can be aborted later when we fire a new request

request = $.ajax({
url: '/data/customer.php',
type: 'POST',
dataType: 'JSON',
//contentType: "text/json; charset=utf-8",
data: {
all: query,
},
success: function(data) {
//console.log(data);
process(data);
}
});
}
});

关于jquery - 如何为 ajax 请求添加延迟以避免性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427889/

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