使用 api 调用 ajax 和 jquery 初始化 Materialize-autocomplete 数据集

initialization Materialize-autocomplete dataset using api call with ajax and jquery

大家早上好, 我在 PHP 应用程序

中使用 materialize.css

我想通过 API 调用来初始化自动完成数据。

.autocomplete ()用JSON数组初始化数据" data ":,

我用 .ajax ({..., url: '/search.php', ... datas}).

但我无法将 datas 注入 .autocomplete (),

我该怎么做?

这里是源代码:

<body>
  <form action="">
    <div class="row">
      <div class="col s12">
        <div class="row">
          <div class="input-field col s6">
            <i class="material-icons prefix">title</i>
            <input id="searchOnAPI" name="name" type="text" class="autocomplete" value="{{ item.name }} ">
            <label for="searchOnAPI">{{ siteData('admin.titre') }}</label>
            <ul id="autocomplete-content" class="autocomplete-content"><li><a></a></li></ul>
          </div>
        </div>
      </div>
    </div>
  </form>

  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
  <script>
    $(document).ready(function () {
      $('#searchOnAPI').keyup(function () {
        $('#autocomplete-content').html('');
        let search = $(this).val();

        if (search !== "") {
          $.ajax({
            type: 'GET',
            url: '/search.php',
            data: 'search=' + encodeURIComponent(search),
            success: function (datas) {
            if (datas !== "") {
              $('#searchOnAPI').autocomplete(datas);
            } else {
            document.getElementById('autocomplete-content').innerHTML = '<ul class="autocomplete-content dropdown-content"><li><a class="black-text">{{ siteData('site.search.nodata') }}</a></li></ul>';
            }
          }
          });
        }
      });
    });
  </script>

我认为问题出在这里:

变量数据 ...

但我不明白错误了。

success: function (datas) {
   if (datas !== "") {
      $('#searchOnAPI').autocomplete(datas);
   }

搜索页面代码: 并致电 API

<?php

if (isset($_GET['search']) && !empty($_GET['search'])) {
    $search = trim(htmlspecialchars($_GET['search']));

    $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL             => "https://api.themoviedb.org/3/search/multi?api_key=". API_KEY ."&language=fr-FR&query=$search",
            CURLOPT_CAINFO          => dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR ."cert.tmdb.cer", //api.themoviedb.org
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_FOLLOWLOCATION  => true,
            CURLOPT_ENCODING        => "",
            CURLOPT_MAXREDIRS       => 10,
            CURLOPT_TIMEOUT         => 10,
            CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST   => "GET"
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);


        $response = json_decode($response, true);
        $err = json_decode($err, true);
        $datas = [];

        if (!is_null($err) || $response === null || !isset($response['results'])) {
            $datas[] = ['No Data' => null];
        } else {

            $response = $response['results'];
            for ($i = 0; $i <= 5; $i++) {
                if (isset($response[$i]['title'])) {
                    $datas[] = $response[$i]['title'] ;
                } elseif (isset($response[$i]['name'])) {
                    $datas[] = $response[$i]['name'];
                }
            }
            
            echo json_encode(array_fill_keys(['data'], array_fill_keys($datas, null)), true);
        }

}

这里是搜索页面json中的apireturn


{
  "data": {
    "O Amor Acontece": null,
    "Quem Quer Namorar Com o Agricultor?": null,
    "O'": null,
    "O Clone": null,
    "Hawaï police d'État": null,
    "O Matador": null
  }
}

欢迎任何建议! .EDD

您的 PHP 代码返回一个带有 'data' 参数的 json 对象,也许您可​​以试试

   if (datas !== "") {
      $('#searchOnAPI').autocomplete(datas.data);
   }

我发现错误:

$.ajax({
    type: 'GET',
    url: '/search.php',
    data: 'search=' + encodeURIComponent(search),
    success: function (datas) {

我没有设置数据类型...

dataType:"json",

像这样

$.ajax({
    type: 'GET',
    dataType:"json",
    url: '/search.php',
    data: 'search=' + encodeURIComponent(search),
    success: function (datas) {

但一切正常。

查找 [Jquery 自动完成 _renderItem 不工作][1]