如何在json文件中搜索值并显示内容

时间:2019-04-18 01:27:26

标签: javascript html json search

这是我的代码:

如果用户在html页面上搜索,我想显示json文件中的详细信息。

json数组详细信息应以html显示

例如:db.json

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
} 

如果用户搜索的Apple itz尺寸和颜色应显示在同一页面上。

我用于搜索json的JS代码是:


<!DOCTYPE html>
<html>
 <head>
  <title>Search Json From Html</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style>
  #result {
   position: absolute;
   width: 100%;
   max-width:870px;
   cursor: pointer;
   overflow-y: auto;
   max-height: 400px;
   box-sizing: border-box;
   z-index: 1001;
  }
  .link-class:hover{
   background-color:#f1f1f1;
  }
  </style>
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:900px;">
   <h2 align="center">Bloomerzz Database</h2>
   <h3 align="center">Get GPVD Complete Link</h3>   
   <br /><br />
   <div align="center">
    <input type="text" name="search" id="search" placeholder="Search Movie Details" class="form-control" />
   </div>
   <ul class="list-group" id="result"></ul>
   <br />
   <p>Copy the Complete URL and paste it in GPPD Website To Download </p>

  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 $.ajaxSetup({ cache: false });
 $('#search').keyup(function(){
  $('#result').html('');
  $('#state').val('');
  var searchField = $('#search').val();
  var expression = new RegExp(searchField, "i");
  $.getJSON('db.json', function(data) {
   $.each(data, function(key, value){
    if (value.name.search(expression) != -1 || value.url.search(expression) != -1)
    {
     $('#result').append('<li class="list-group-item link-class"><img src="'+value.image+'" height="80" width="80" class="img-thumbnail" />  <span class="text-muted">'+value.url+'</span> | '+value.name+' </li>');
    }
   });   
  });
 });

 $('#result').on('click', 'li', function() {
  var click_text = $(this).text().split('|');
  $('#search').val($.trim(click_text[0]));
  $("#result").html('');
 });
});
</script>

需要帮助...

0 个答案:

没有答案