如何在更改nodejs中的选择框时处理来自客户端的大量请求
我在一个州的每个区都有大量的服务器学院和学校名单。
在用户的注册页面中,我向他询问区域,当他选择一个区域时,我将请求发送到具有区域名称作为请求主体的nodejs。服务器读取分区并将大学列表发送到客户端,我将列表放在选择框中。 (我正在向nodejs发送ajax请求)
问题是,如果我过快地单击区域选择框或使用箭头键,那么它会被所有内部多个请求卡住吗?
在服务器和客户端改进此方法的方法有哪些,以及如何有效地处理选择框的快速选择更改?
var timer = 0 ;
$('#select_district').on('change', function district_selection_changed() {
clearTimeout(timer) ;
timer = setTimeout(function(){
$.ajax({
type: "post",
url: "/getcolleges",
data: {
state: $("#select_state").val(),
district: $("#select_district").val()
},
dataType: "json",
success: function (response) {
$("#select_college").html("");
collegenameelement = document.getElementById("collegenameslist") ;
response.forEach((ele) => collegenameelement.innerHTML = collegenameelement.innerHTML+
`<option>${ele}</option>`)
}
})
} , 500) ;
回答如下:
我认为最好在上次调用请求后的短时间内延迟执行请求。这种行为通常被称为debounce
函数,它受到许多实用程序库的支持,如Underscore,Lodash等......
如果您不想仅为一个函数安装整个库,则可以检查其代码并实现自己的代码。
如果请求仍在处理中,您还可以阻止用户选择新区域,并在需要时向他们显示加载图标。