简体   繁体   English

从json获取结果

[英]Fetch results from json

I have a bootstrap live search for pixabay api. 我有一个Bootstrap实时搜索的api。 But I have a problem with results from pixabay. 但是我对结果的查询有疑问。 For example, I want to search images with query flowers but its returning results when i start typing. 例如,我想搜索带有查询花的图像,但是当我开始键入时返回的结果。 I type flo and i have a images with tag flo. 我输入flo,并且我有一个带有flo的图像。 At the end I have links to images with tag flow flowe and flowers. 最后,我链接到带有标签流和花朵的图像。 How to prevent this situation? 如何预防这种情况?

$('#search').keyup(function(){  
    var q = $(this).val().toLowerCase();
    var API_KEY = 'xx';
    var URL = "https://pixabay.com/api/?key="+API_KEY+"&q="+encodeURIComponent(q);
    $.getJSON(URL, function(data){
    if (parseInt(data.totalHits) > 0)
        $.each(data.hits, function(i, hit){ 
        htmlData = '<div class="col"><img src="'+hit.largeImageURL+'" class="img-fluid" alt=""/></div>';
         $('.modal-body').append(htmlData);
    });
    else
        console.log('No hits');
    });
});

How to load expected images dynamically into modal? 如何将期望的图像动态加载为模态? Also how to remove images when i remove few chars from search bar? 另外,当我从搜索栏中删除一些字符时,如何删除图像? If i put flowers It load flowers into modal, but when i type cars I want to show only cars, not flowers and cars. 如果我放花,它将花加载到模式中,但是当我键入汽车时,我只想显示汽车,而不是花和汽车。

There's two things you need to do to fix this behaviour. 要解决此问题,您需要做两件事。 The first is to 'debounce' the event so that the AJAX request is only made when typing has finished for a short delay, eg. 第一种是“消除”该事件,以便仅在短暂延迟下完成键入后才发出AJAX请求。 150ms. 150毫秒。 The second is to wipe all previous results from the UI before you add the latest ones. 第二种是在添加最新结果之前,先清除用户界面中所有以前的结果。 Try this: 尝试这个:

var searchTimeout;

$('#search').keyup(function() {
  var q = $(this).val().toLowerCase();
  var API_KEY = 'xx';
  var URL = "https://pixabay.com/api/?key=" + API_KEY + "&q=" + encodeURIComponent(q);
  clearTimeout(searchTimeout);

  searchTimeout = setTimeout(function() {
    $.getJSON(URL, function(data) {
      if (parseInt(data.totalHits) > 0) {
        var htmlData = data.hits.map(function(hit) {
          return `<div class="col"><img src="${hit.largeImageURL}" class="img-fluid" alt=""/></div>`;
        });
        $('.modal-body').html(htmlData); // note 'html()' here. It will overwrite all existing content
      } else {
        console.log('No hits');
      }
    });
  }, 150);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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