【问题标题】:Laravel ajax autocomplete very slowLaravel ajax 自动完成非常慢
【发布时间】:2020-02-26 16:09:14
【问题描述】:

我的应用程序中有以下 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 上运行它

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

【问题讨论】:

    标签: php ajax jquery-ui-autocomplete laravel-6


    【解决方案1】:

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

    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 字段来预填充

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

    【讨论】:

    • 另一种方法是使用原始查询(数据库查询构建器)而不是雄辩的查询构建器。
    • 另外,也可能是操作系统性能问题或服务器问题(Apache/Nginx),因为启动时间 3s 太长了。
    • db 查询没问题。是应用程序启动时间过长
    • 这可能是服务器(Apache/Nginx)的一些网络相关问题。请检查日志。或者尝试使用 WAMP 服务器运行。
    【解决方案2】:

    所以我已经安装了https://github.com/winnfsd/vagrant-winnfsd

    $ vagrant plugin install vagrant-winnfsd
    

    更新了 Homestead.yaml 如下:

    folders:
    - map: ~/code/project1
      to: /home/vagrant/project1
      type: "nfs"
    

    运行

    vagrant up --provision
    

    现在启动时间已降至 500 毫秒

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-11
      • 2021-11-13
      • 2019-10-04
      • 1970-01-01
      • 2013-06-16
      • 2021-11-30
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多