将图像添加到json搜索栏

时间:2016-04-20 16:01:38

标签: javascript jquery json ajax image

我使用ajax和json创建了一个搜索栏,但是我很难添加图片,只要我尝试添加图片就会停止搜索功能。这是我试图添加图像的代码:

  output +='<img src="images/' + val.imageref +'" />';

这是json文件中一些代码的信息:

[{
"brand": "Pedigree",
"product": "Dentastix Fresh",
"type": "Food",
"imageref": "images/dentastix.jpg",
"price": "£5.00"
}, {
"brand": "Trixie",
"product": "Automatic Food Dispenser Tx2",
"type": "Food bowl",
"imageref": "images/dogbowl.jpg",
"price": "£10.00"

有没有人有任何关于如何添加图片的建议?

整个代码:

   <label for="search">Search <a href="#"><img src="images/search.jpg"></a></label><input type="search" name="search" class="tool" title="Type in a product name or category to get started" id="search" placeholder="Product..." />


                </div>
      <div id="update"></div>
      <script>
     $('#search').keyup(function(){
      var searchField = $('#search').val();
     var myExp = new RegExp(searchField, 'i');
     $.getJSON('search.json', function(data){
      var output = '<ul class="searchresult">';
      $.each(data, function(key, val){
        if((val.brand.search(myExp) != -1) || (val.type.search(myExp) != -1)) {
          output +='<h1>' + val.brand + '</h1>';
          output +='<h2>' + val.product + '</h2>';
          output +='<img src="images/' + val.type +'/'+ val.brand + val.product + '.jpg" />';
          output +='<p>' + val.price +  '</p>';
          output +='</li>';
        }
      });
      output += '</ul>';
      $('#update').html(output);
    });
  });
  </script>

1 个答案:

答案 0 :(得分:0)

当您在输出变量中引用路径时,您似乎正在复制图像目录。除非images / images / dogbowl.jpg是您的图像所在。您可以尝试使用托管图像进行测试,以确保它不是文件路径问题。

您是否可以在codepen或其他具有更多详细信息的服务中包含代码示例?