如何在 Laravel 和 ajax 中优化 Fetch 查询

问题描述 投票:0回答:1

我正在尝试获取包含 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
      });
    }
jquery ajax laravel laravel-livewire
1个回答
0
投票

如果您想优化用户在输入字段中输入城市时的搜索方法,您需要在 JS 中使用以下内容设置条件:

  1. 输入字符超过x长度后才启动ajax。这样 SQL 查询将返回更准确的数据。
  2. 仅在y毫秒后启动ajax,这样http请求就不会总是执行,从而仅在需要时执行。

下面是您可以尝试的代码:

$(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。

© www.soinside.com 2019 - 2024. All rights reserved.