簡體   English   中英

自動完成搜索中的建議框沒有出現

[英]suggestion box in autocomplete search doesn't appear

我想使用Photon服務創建一個自動完成輸入框。 我試圖做的是創建一個返回結果的ajax請求。 通過輸入地址的幾個字母,Photon API 應該向我顯示結果,如圖所示:

在此處輸入圖片說明

我所寫的是以下內容:

html

  <div class="frmSearch">
    <input type="text" id="search-box" placeholder="Country Name" />
    <div id="suggesstion-box"></div>
</div>

js

$("#search-box").keyup(function(){
        $.ajax({
        type: "GET",
        url: "http://photon.komoot.de/api/?q=" + $("#search-box").val(),

        beforeSend: function(){
            $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
        },
        success: function(results){

       var aList = results.features;
       var aOptions = [];
       for (i=0; i < aList.length; i++) {
           optKey = aList[i].geometry.coordinates[0]+','+aList[i].geometry.coordinates[1];
           optLabel = aList[i].properties.name+', '+aList[i].properties.street+' '+aList[i].properties.housenumber+', '+
              aList[i].properties.city+', '+aList[i].properties.postcode;
           aOptions.push({
              "value": optKey,
              "label": optLabel
           });
       }

   

            $("#suggesstion-box").show();
            $("#suggesstion-box").html(aOptions);
            $("#search-box").css("background","#FFF");
        }
        });
    });

API 調用效果很好,但我的意見箱沒有出現。我做錯了什么?

您不能直接使用html()函數添加對象。 你只能傳遞string

所以你需要將你的對象數組解析為string

 $("#search-box").keyup(function() { $.ajax({ type: "GET", url: "https://photon.komoot.de/api/?q=" + $("#search-box").val(), beforeSend: function() { $("#search-box").css("background", "#FFF url(LoaderIcon.gif) no-repeat 165px"); }, success: function(results) { var aList = results.features; var aOptions = []; let htmlVal = ''; for (i = 0; i < aList.length; i++) { optKey = aList[i].geometry.coordinates[0] + ',' + aList[i].geometry.coordinates[1]; optLabel = aList[i].properties.name + ', ' + aList[i].properties.street + ' ' + aList[i].properties.housenumber + ', ' + aList[i].properties.city + ', ' + aList[i].properties.postcode; aOptions.push({ "value": optKey, "label": optLabel }); htmlVal += `${optKey} ${optLabel} <br />`; // add each value to htmlVal } $("#suggesstion-box").show(); $("#suggesstion-box").html(htmlVal); $("#search-box").css("background", "#FFF"); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="frmSearch"> <input type="text" id="search-box" placeholder="Country Name" /> <div id="suggesstion-box"></div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM