首页 > 解决方案 > 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 上运行它

任何想法我可以如何调整它,因为它目前不是很有用?

标签: phpajaxjquery-ui-autocompletelaravel-6

解决方案


可以通过限制记录和限制您获取的数据来做一个小的改进,如下所示 -

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 字段即可进行预填充

获取较少量的数据是一个小技巧,我希望它会提高一些性能。


推荐阅读