php - Laravel ajax 自动完成非常慢
问题描述
我的应用程序中有以下 jquery 自动完成功能(https://github.com/devbridge/jQuery-Autocomplete)
但是它非常慢 - 渲染大约需要 4 秒。我安装了调试栏,时间线显示启动占用了将近 3 秒,应用程序占用了 1 秒,实际数据库查询为 44 毫秒。
这是我的 jquery 自动完成实现:
window.locationAutoCompleteSettings = {
serviceUrl: "/location-lookup",
minChars: 2,
paramName: "term",
showNoSuggestionNotice: false,
onSearchStart: function (query) {
$(this).closest(".js-clear-input").find(".js-clear-input-trigger").addClass("clear-input-spinner")
},
onSearchComplete: function (query) {
$(this).closest(".js-clear-input").find(".js-clear-input-trigger").removeClass("clear-input-spinner")
},
transformResult: function (response) {
var data = JSON.parse(response);
return {
suggestions: $.map(data, function (item) {
return {
value: item.name,
data: item.id
}
})
};
},
onSelect: function (suggestion) {
var e = $(this).closest(".js-lookup-container").find(".js-location-id");
e.val(suggestion.data);
var f = suggestion.value, b = $(".js-location-description");
if (b.length && b.val() == "") {
b.val(f).trigger("change")
}
}
};
$(".js-location-lookup").autocomplete(window.locationAutoCompleteSettings);
这是我的控制器方法:
public function locationLookup(Request $request)
{
$term = $request->input('term');
$locations = $this->locationRepository->getByName($term)->get();
return response()->json($locations);
}
作为记录,我在 Windows 10 机器上使用 php 7.4 在 Homestead 上运行它
任何想法我可以如何调整它,因为它目前不是很有用?
解决方案
可以通过限制记录和限制您获取的数据来做一个小的改进,如下所示 -
public function locationLookup(Request $request)
{
$term = $request->input('term');
$locations = $this->locationRepository->getByName($term)->take(10)->get(['id', 'name']);
return response()->json($locations);
}
- 这里假设您一次只预填充 10 条记录用于自动建议
- 而且您只需要 id 和 name 字段即可进行预填充
获取较少量的数据是一个小技巧,我希望它会提高一些性能。
推荐阅读
- django - Django:输入密码后显示视图
- javascript - 如何使用 keras.js 进行预测
- python - 在 pandas 中计数并将输出分配给变量
- gcc - 包括本地机器上 Boost 区域的路径
- java - 在 spring-boot 中使用 RestTemplate 返回 404
- python - 使用 Python 对 wav 文件每秒执行 FFT
- unix - Unix命令在一个文件中查找具有在另一个文件中找不到键的行
- node.js - 尝试推送时 Mongoose 数组为空
- pytorch - 与 pytorch 权重的元素乘法
- django - 致命:用户的密码验证失败/但用户存在