繁体   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