Javascript在

时间:2017-06-21 13:52:02

标签: javascript jquery algolia

我使用algolia进行实时搜索。

<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value);" placeholder="Search">

我的js就像这样

 var client = algoliasearch('''', '''');
        var index = client.initIndex('businesses'); 
    function search_data(search_value) {
    index.search(search_value, function searchDone(err, content) {
      if (err) {
        console.error(err);
        return;
      }

      for (var h in content.hits)
      console.log(content);
        console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());

    });

    // with params
    index.search(search_value, {
      attributesToRetrieve: ['name'],
      hitsPerPage: 50
    }, function searchDone(err, content) {
      if (err) {
        console.error(err);
        return;
      }

      for (var h in content.hits) {
        console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].toString());
      }
    });
    }

控制台日志中的输出如下所示:

Object{
  hits: Array(2),
  nbHits: 2,
  page: 0,
  nbPages: 1,
  hitsPerPage: 20…
}exhaustiveNbHits: truehits: Array(2)0: Object1: Objectapi_key: 10565created_at: nullemail: "n/a"facebook_business: nullgallery_id: nullid: 1image: nullinstagram_business: nulllogo: nullname: "Odeon Cinema"objectID: "1"twitter_business: nulltype: "3"updated_at: nulluser_id: 1

但现在我被卡住了。如何在页面上输出? 从这些结果我想输出所有结果,显示名称

//修改

    var client = algoliasearch('75RQSC1OHE', 'f06169611a53cb7e026f364739162cb9');
    var index = client.initIndex('businesses'); 
function search_data(search_value) {
    index.search(search_value, {
        attributesToRetrieve: ['name'],
        hitsPerPage: 5
    }, function searchDone(err, content) {
    if (err) {
    console.error(err);
    return;
  }
  for (var h in content.hits) {
    $('.test').append("<li>" + content.hits[h].name + "</li>");
  }
});
}

1 个答案:

答案 0 :(得分:1)

在追加之前清除.test。在for循环之前使用$('.test').html('');