我正在尝试获取包含 40,000 多个城市的城市列表,我的问题是如何优化,因为我的浏览器在加载城市时保持响应。 在 Laravel 控制器中,我有,
public function getCities(Request $request)
{
$query = $request->input('query');
$cities = UsCities::where('CITY', 'like', '%' . $query . '%')->get()->pluck('CITY')->toArray();
return response()->json($cities);
}
和ajax代码
$.ajax({
method: "GET",
url: '{{ route("get.cities")}}',
data: { query: $('#city-selected').val() },
success: function (response) {
townsTags = response;
startAutocomplete(townsTags, "#city-selected");
}
});
function startAutocomplete(availableTags, inputSelector) {
$(inputSelector).autocomplete({
source: availableTags
});
}
如果您想优化用户在输入字段中输入城市时的搜索方法,您需要在 JS 中使用以下内容设置条件:
下面是您可以尝试的代码:
$(document).ready(function() {
// create a timer variable for setTimeout
var inputTimer;
function handleInputChange() {
$('#loading').show(); // much better add a loading somewhere so that users can see that something is happening
// clear the timer variable for setTimeout
clearTimeout(inputTimer);
var cityVal = $(this).val();
// start ajax when input is 3 or more character length so that it will not always submit a request to your backend
if (cityVal.length >= 3) {
// setTimeout so that it will only execute the ajax after 500 miliseconds where there is no more incoming changes
inputTimer = setTimeout(function() {
// swap console.log to your ajax
console.log("Input value changed:", cityVal);
$('#loading').hide(); // add inside 「success」 method of ajax so that loading will hide after executing irregardless of success or error
}, 500);
} else {
console.log("please enter at least 3 characters")
}
}
$('#city-selected').on('input', handleInputChange);
});
根据您想要开始执行的时间更改 3 或 500。