简体   繁体   中英

Cannot render ResultList using autoComplete.js

I'm testing autoComplete.js to get suggestions, but I cannot make ResultList to be shown. This is my simple input field:

<script src="https://cdn.jsdelivr.net/npm/@tarekraafat/autocomplete.js@7.2.0/dist/js/autoComplete.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tarekraafat/autocomplete.js@7.2.0/dist/css/autoComplete.min.css">

<input type="text" id="autocomplete" name="fname">

And this is my JavaScript code:

const autoCompletejs = new autoComplete({
  data: {
    src: async () => suggest("party"),
    key: ["cname"],
    cache: false
  },
  trigger: {
    event: ["input"]
  },
  selector: "#autocomplete",
  resultsList: {
    render: true,
    container: source => {
      source.setAttribute("id", "company_name");
    },
    destination: document.querySelector("#autoComplete"),
    position: "afterend",
    element: "ul"
  }
});

Async function to get suggestions dynamically:

async function suggest(resource) {
  const query = document.querySelector("#autoComplete").value;
  var API_KEY = "6397a5215604df4cdda1109d8cdc08497d8284b2";
  const response = await fetch("https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/" + resource, {
    method: 'POST',
    headers: {
      'Authorization': "Token " + API_KEY,
      'Content-Type': "application/json"
    },
    body: "{ \"query\": \"" + query + "\" }"
  });
  const data = await response.json();            
  return data;
}

i think you bug is at return data myabe this is returning your data but in your console not in your input but i'm not sure also i think you have to do something like that

autocomplete(document.getElementById("autocomplete"), data); or something like that hope it helps

Your suggest function returns the data inside of suggestions object which needs to be selected as shown below and in the JSFiddle link as well.

async function suggest(resource) {
  const query = document.querySelector("#autoComplete").value;
  var API_KEY = "6397a5215604df4cdda1109d8cdc08497d8284b2";
  const response = await fetch("https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/" + resource, {
    method: 'POST',
    headers: {
      'Authorization': "Token " + API_KEY,
      'Content-Type': "application/json"
    },
    body: "{ \"query\": \"" + query + "\" }"
  });
  const data = await response.json();            
  return data.suggestions;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM