简体   繁体   English

仅在选择过滤器时显示JSON结果

[英]Showing results from JSON only when filter is selected

Objective 目的

I want display results only when it's respective state is selected. 我只希望显示结果处于选中状态。 Currently all results are shown by default when the page loads. 当前,默认情况下,页面加载时会显示所有结果。

在此处输入图片说明

I do not want anything to load by default. 默认情况下,我不希望加载任何内容。 When a state is selected then those results should populate. 选择状态后,这些结果应填充。

Background 背景

I have a location selection feature that I am working on at this CodePen . 我在此CodePen中正在使用位置选择功能。

It used MustacheJS for templating 它使用MustacheJS进行模板制作

and is populated by data in a JSON file by this script 并通过此脚本由JSON文件中的数据填充

$(function() {
  $.getJSON('https://s3-us-west-2.amazonaws.com/s.cdpn.io/161741/labs.js', function(data) {
    var template = $('#labsListStates').html();
    var html = Mustache.to_html(template, data);
    $('#states').html(html);
  });
});

The results can be filtered by state with. 结果可以按状态进行过滤。 It runs on this script 它在此脚本上运行

/* Filter for locations */
$('#lab-state-select').on('change', function (e) {
  e.preventDefault();
  var cat = $(this).val();
  var nam = $(this).val();
  $('#states > div').hide();
  $('#states > div[data-category-type="'+cat+'"][data-category-name="'+nam+'"]').show();
});

Problems 问题

I know that this is sloppy. 我知道这很草率。 I am not using pure JSON but actually creating a Javascript object. 我不是使用纯JSON,而是实际上创建了一个Javascript对象。 And even named the file to end with .js so that it would work. 甚至命名该文件以.js结尾,以便它可以正常工作。 I read about how that is a bad practice at http://www.kryptonite-dove.com/blog/load-json-file-locally-using-pure-javascript 我在http://www.kryptonite-dove.com/blog/load-json-file-locally-using-pure-javascript中了解了这是一种不良做法

That taught me to look into a XMLHttpRequest . 这就教会了我研究XMLHttpRequest But even implementing that I am still confused how to display the data I need when I need it. 但是即使实现了这一点,我仍然对如何在需要时显示所需数据感到困惑。 I think I am on the correct track by looking into the .on() but would appreciate some additional help. 通过查看.on(),我认为我走在正确的轨道上,但希望您能获得一些其他帮助。

You simply use $('#states > div').hide(); 您只需使用$('#states > div').hide(); to hide the data right after you load the data: $('#states').html(html); 在加载数据后立即隐藏数据: $('#states').html(html); .

You can check out the fork here: http://codepen.io/anon/pen/lBims 您可以在此处检出叉子: http : //codepen.io/anon/pen/lBims

As for getting the JSON file, you can simply return it with any file type. 至于获取JSON文件,您可以简单地返回任何文件类型。 You don't have to use a .js extension if it's just pure JSON output. 如果它只是纯JSON输出,则不必使用.js扩展名。 And JSON is just a stringified representation for Javascript objects, so it's fine treating JSON as an object. JSON只是Javascript对象的字符串表示形式,因此将JSON作为对象很好。 In Fact that's what you're supposed to do. 实际上,这就是您应该做的。 JSON = JavaScript Object Notation. JSON = JavaScript对象表示法。

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

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