使用javascript从JSON文件中获取数据并将其插入下拉列表

使用javascript从JSON文件中获取数据并将其插入下拉列表,javascript,html,json,Javascript,Html,Json,我有一个JSON文件,其中包含大量数据,如: [ { "manufacturer": "Samsung", "gadget": "Smart Phone", "model": "Note 9" }, { "manufacturer": "Apple", "gadget": "Smart Phone", "model": "iPhone 5" }, ...] 我需要用javascri

我有一个JSON文件,其中包含大量数据,如:

[  {  
       "manufacturer": "Samsung",
       "gadget": "Smart Phone",
       "model": "Note 9"
   },
   {  
       "manufacturer": "Apple",
       "gadget": "Smart Phone",
       "model": "iPhone 5"
   }, 
...]
我需要用javascript获取这些数据,然后将其发送到HTML文件中的select标记

这就是我的HTML的外观,我也会包括js,但我不知道如何启动或初始化JSON并将其发送到HTML

<main>
  <section id="welcome-section-shop">
    <div id="welcome-header">
      <h2>Web shop</h2>
    </div>
  </section>
  <section class="shop-section">
    <div id="shop-header">
      <div id="shop-div">
        <h1>Step 1: Select manufacturer</h1>
        <hr id="shop-hr">
        <select class="select-option" id="select" name="select">
          <option value="">Select manufacturer</option>
        </select>
        <h1>Step 2: Select gadget type</h1>
        <hr id="shop-hr">
        <select class="select-option" id="select" name="select">
          <option value="">Select gadget</option>
        </select>
        <h1>Step 3: Select model</h1>
        <hr id="shop-hr">
        <select class="select-option" id="select" name="select">
          <option value="">Select model</option>
        </select>
      </div>
    </div>
  </section>
</main>
为您的代码

    <section id="welcome-section-shop">
    <div id="welcome-header">
        <h2>Web shop</h2>
    </div>
</section>

<section class="shop-section">
    <div id="shop-header">
        <div id="shop-div">

            <h1>Step 1: Select manufacturer</h1><hr id="shop-hr">
            <select class="select-option" id="select1" name="select">
                <option value="">Select manufacturer</option>
            </select>
            <h1>Step 2: Select gadget type</h1><hr id="shop-hr">
            <select class="select-option" id="select2" name="select">
                <option value="">Select gadget</option>
            </select>
            <h1>Step 3: Select model</h1><hr id="shop-hr">
            <select class="select-option" id="select3" name="select">
                <option value="">Select model</option>
            </select>

        </div>

    </div>
</section>
<script>
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = xhttp.responseJSON;
            for(var i in data){
                var option1 = document.createElement('option');
                var option2 = document.createElement('option');
                var option3 = document.createElement('option');
                option1.text = data[i]["manufacturer"];
                option2.text = data[i]["gadget"];
                option3.text = data[i]["model"];
                document.getElementById('select1').appendChild(option1);
                document.getElementById('select2').appendChild(option2);
                document.getElementById('select3').appendChild(option3);

            }
        }
    };
    xhttp.open("GET", "filename", true);
    xhttp.send();
</script>
您的数据将类似[{text:abc,value:abc},{……]

使用加载json文件

const handleAsJson = response => response.json();
const handleError = console.error // or some such;
fetch('/url/to/file.json')
  .then(handleAsJson)
  .catch(handleError);
我建议使用名为的轻量级模板库来构造DOM

<section id="welcome-section-shop">
    <div id="welcome-header">
        <h2>Web shop</h2>
    </div>
</section>

<section class="shop-section">
<div id="shop-header">
    <div id="shop-div">

        <h1>Step 1: Select manufacturer</h1><hr id="shop-hr">
        <select class="select-option" id="manufacturer-select" name="select">
            <option value="">Select manufacturer</option>
        </select>
        <h1>Step 2: Select gadget type</h1><hr id="shop-hr">
        <select class="select-option" id="gadget-select" name="select">
            <option value="">Select gadget</option>
        </select>  
        <h1>Step 3: Select model</h1><hr id="shop-hr">
        <select class="select-option" id="model-select" name="select">
            <option value="">Select model</option>
        </select>         

    </div>

</div>
</section>

<script type="module">
  import { render, html } from 'https://unpkg.com/lit-html/lit-html.js?module';

  const manufacturerSelect = document.getElementById('manufacturer-select')
  const modelSelect = document.getElementById('model-select')
  const gadgetSelect = document.getElementById('gadget-select')

  // converts array of items into more manageable object 
  const traverse = items => items.reduce((acc, { gadget, manufacturer, model }) => ({
    gadgets: [...acc.gadgets, gadget],
    manufacturers: [...acc.manufacturer, gadget],
    models: [...acc.models, gadget],
  }), {})

  // defines the template for an option element with interpolated string attribute and content
  const optionTpl = string => html`<option value="${string}">${string}</option>`;
  // renders all option values to each select element
  const renderTemplates = ({ gadget, manufacturer, model }) => {
    render(html`<option value="">Select manufacturer</option>${manufacturer.map(optionTpl)}`, manufacturerSelect)
    render(html`<option value="">Select model</option>${model.map(optionTpl)}`, modelSelect)
    render(html`<option value="">Select gadget</option>${gadget.map(optionTpl)}`, gadgetSelect)
  }

  const handleAsJson = response => response.json();
  const handleError = console.error // or some such;

  fetch('/url/to/file.json')
    .then(handleAsJson)
    .then(traverse)
    .then(renderTemplates)
    .catch(handleError);
</script>

您也可以考虑为您的DoPrdon定义一个自定义元素,它将使用占位符属性来定义字符串,以及字符串选项作为属性。请注意,此时,您必须访问JavaScript的选择值,因为尚未准备好。 HTML:

剧本

const xhr = new XMLHttpRequest()
const url = 'path/to/file.json'
xhr.onreadystatechange = function() {
  if ((this.readyState == 4) && (this.status == 200)) {
    const array = JSON.parse(this.responseText)
    const formatted = formatData(array)
    start(formatted)
  }
}

function formatData(array) {
  const res = {}
  for (let item of array) {
    const gadgets = res[item.manufacturer] || (res[item.manufacturer] = {})
    const models = gadgets[item.gadget] || (gadgets[item.gadget] = [])
    models.push(item.model)
  }
  return res
}

function start(data) {

  const selectManufacturer = document.getElementById('select-manufacturer')
  const selectGadget = document.getElementById('select-gadget')
  const selectModel = document.getElementById('select-model')
  for (let manufacturer in data) {
    selectManufacturer.appendChild(createOption(manufacturer))
  }

  let gadgets

  selectManufacturer.addEventListener('change', () => {
    gadgets = data[selectManufacturer.value]
    selectGadget.innerHTML = ''
    selectGadget.appendChild(placeholderOption('gadget'))
    for (let gadget in gadgets) {
      selectGadget.appendChild(createOption(gadget))
    }
    selectGadget.disabled = false
    selectModel.innerHTML = ''
    selectModel.appendChild(placeholderOption('model'))
    selectModel.disabled = true
    const placeholder = document.getElementById('manufacturer-placeholder')
    if (placeholder) selectManufacturer.removeChild(placeholder)
  })

  selectGadget.addEventListener('change', () => {
    const models = gadgets[selectGadget.value]
    selectModel.innerHTML = ''
    selectModel.appendChild(placeholderOption('model'))
    for (let model of models) {
      selectModel.appendChild(createOption(model))
    }
    selectModel.disabled = false
    const placeholder = document.getElementById('gadget-placeholder')
    if (placeholder) selectGadget.removeChild(placeholder)
  })

  selectModel.addEventListener('change', () => {
    const placeholder = document.getElementById('gadget-placeholder')
    if (placeholder) selectModel.removeChild(placeholder)
  })
}

function createOption(value, text) {
  if (text == undefined) text = value
  let opt = document.createElement('option')
  opt.value = value
  opt.innerHTML = text
  return opt
}
function placeholderOption(type) {
  let opt = createOption('', `Select ${type}`)
  opt.id = `${type}-placeholder`
  return opt
}

嘿,快问!在JSON中,我有以下数据:3家制造商,三星苹果和华为,3种不同的小玩意类型,智能手机、平板电脑、智能手表和每种小玩意类型的5+种不同型号。在这种情况下,我如何组织JSON?可能是这样的?{三星:{智能手机:[注9,Galaxy S8],平板电脑:[abc,abc],智能手表:[abc,abc]},苹果:{智能手机:[注9,Galaxy S8],平板电脑:[],智能手表:[abc,abc]},华为:{智能手机:[注9,Galaxy S8],平板电脑:[abc,abc],智能手表:[abc,abc]}这是制作e Reliable下拉列表的最简单方法。formatData函数将按照您在问题中介绍的方式格式化您的数据……如果您的JSON是按这种方式组织的,则跳过formatData函数这两种方式都不起作用,但您的代码似乎非常正常:
<section id="welcome-section-shop">
    <div id="welcome-header">
        <h2>Web shop</h2>
    </div>
</section>

<section class="shop-section">
<div id="shop-header">
    <div id="shop-div">

        <h1>Step 1: Select manufacturer</h1><hr id="shop-hr">
        <select class="select-option" id="manufacturer-select" name="select">
            <option value="">Select manufacturer</option>
        </select>
        <h1>Step 2: Select gadget type</h1><hr id="shop-hr">
        <select class="select-option" id="gadget-select" name="select">
            <option value="">Select gadget</option>
        </select>  
        <h1>Step 3: Select model</h1><hr id="shop-hr">
        <select class="select-option" id="model-select" name="select">
            <option value="">Select model</option>
        </select>         

    </div>

</div>
</section>

<script type="module">
  import { render, html } from 'https://unpkg.com/lit-html/lit-html.js?module';

  const manufacturerSelect = document.getElementById('manufacturer-select')
  const modelSelect = document.getElementById('model-select')
  const gadgetSelect = document.getElementById('gadget-select')

  // converts array of items into more manageable object 
  const traverse = items => items.reduce((acc, { gadget, manufacturer, model }) => ({
    gadgets: [...acc.gadgets, gadget],
    manufacturers: [...acc.manufacturer, gadget],
    models: [...acc.models, gadget],
  }), {})

  // defines the template for an option element with interpolated string attribute and content
  const optionTpl = string => html`<option value="${string}">${string}</option>`;
  // renders all option values to each select element
  const renderTemplates = ({ gadget, manufacturer, model }) => {
    render(html`<option value="">Select manufacturer</option>${manufacturer.map(optionTpl)}`, manufacturerSelect)
    render(html`<option value="">Select model</option>${model.map(optionTpl)}`, modelSelect)
    render(html`<option value="">Select gadget</option>${gadget.map(optionTpl)}`, gadgetSelect)
  }

  const handleAsJson = response => response.json();
  const handleError = console.error // or some such;

  fetch('/url/to/file.json')
    .then(handleAsJson)
    .then(traverse)
    .then(renderTemplates)
    .catch(handleError);
</script>
<section id="welcome-section-shop">
  <div id="welcome-header">
    <h2>Web shop</h2>
  </div>
</section>

<section class="shop-section">
  <div id="shop-header">
    <div id="shop-div"></div>
  </div>
</section>


<script type="module">
  import { render } from 'https://unpkg.com/lit-html/lit-html.js?module';
  import { LitElement, html, css } from 'https://unpkg.com/lit-element/lit-element.js?module';

const traverse = items => items.reduce(({gadgets = [], manufacturers = [], models = []}, { gadget, manufacturer, model }) => ({
  gadgets: [...gadgets, gadget],
  manufacturers: [...manufacturer, manufacturer],
  models: [...models, model],
}), {})

const optionTpl = string => html`<option value="${string}">${string}</option>`;

customElements.define('shop-dropdown', class extends LitElement {
  static get properties() {
    return {
      placeholder: { type: String },
      items: { type: Array },
    };
  }

  static get styles() {
    return css`
      :host {
        display: block;
      }

      select {
        /*...*/
      }
    `
  }

  get value() {
    return (
      this.shadowRoot &&
      this.shadowRoot.querySelector('select') &&
      this.shadowRoot.querySelector('select').value
    );
  }

  render() {
    return html`
    <select>
      <option>${this.placeholder}</option>
      ${this.items.map(optionTpl)}
    </select>
    `
  }
});

const handleAsJson = response => response.json();
const handleError = console.error // or some such;

const renderTemplates = ({ gadgets, models, manufacturers }) => render(html`
<h1>Step 1: Select manufacturer</h1>
<hr/>
<shop-select placeholder="Select manufacturer" .items=${manufacturers}></shop-select>

<h1>Step 2: Select gadget type</h1>
<hr/>
<shop-select placeholder="Select gadget" .items=${gadgets}></shop-select>

<h1>Step 3: Select model</h1>
<hr/>
<shop-select placeholder="Select model" .items=${models}></shop-select>
`, document.getElementById('shop-div'))

  fetch('/url/to/file.json')
    .then(handleAsJson)
    .then(traverse)
    .then(renderTemplates)
    .catch(handleError);
</script>
<h1>Step 1: Select manufacturer</h1><hr id="shop-hr">
<select class="select-option" id="select-manufacturer" name="manufacturer">
  <option id="manufacturer-placeholder" value="">Select manufacturer</option>
</select>

<h1>Step 2: Select gadget type</h1><hr id="shop-hr">
<select class="select-option" id="select-gadget" name="gadget" disabled>
  <option id="gadget-placeholder" value="">Select gadget</option>
</select>  

<h1>Step 3: Select model</h1><hr id="shop-hr">
<select class="select-option" id="select-model" name="model" disabled>
  <option id="model-placeholder" value="">Select model</option>
</select>         
{
  "Samsung": {
    "Smart Phone": [ "Note 9", ],
    // ...
  },
  "Apple": {
    "Smart Phone: [ "iPhone 5", /* ... */ ],
    // ...
  },
  // ...
}
const xhr = new XMLHttpRequest()
const url = 'path/to/file.json'
xhr.onreadystatechange = function() {
  if ((this.readyState == 4) && (this.status == 200)) {
    const array = JSON.parse(this.responseText)
    const formatted = formatData(array)
    start(formatted)
  }
}

function formatData(array) {
  const res = {}
  for (let item of array) {
    const gadgets = res[item.manufacturer] || (res[item.manufacturer] = {})
    const models = gadgets[item.gadget] || (gadgets[item.gadget] = [])
    models.push(item.model)
  }
  return res
}

function start(data) {

  const selectManufacturer = document.getElementById('select-manufacturer')
  const selectGadget = document.getElementById('select-gadget')
  const selectModel = document.getElementById('select-model')
  for (let manufacturer in data) {
    selectManufacturer.appendChild(createOption(manufacturer))
  }

  let gadgets

  selectManufacturer.addEventListener('change', () => {
    gadgets = data[selectManufacturer.value]
    selectGadget.innerHTML = ''
    selectGadget.appendChild(placeholderOption('gadget'))
    for (let gadget in gadgets) {
      selectGadget.appendChild(createOption(gadget))
    }
    selectGadget.disabled = false
    selectModel.innerHTML = ''
    selectModel.appendChild(placeholderOption('model'))
    selectModel.disabled = true
    const placeholder = document.getElementById('manufacturer-placeholder')
    if (placeholder) selectManufacturer.removeChild(placeholder)
  })

  selectGadget.addEventListener('change', () => {
    const models = gadgets[selectGadget.value]
    selectModel.innerHTML = ''
    selectModel.appendChild(placeholderOption('model'))
    for (let model of models) {
      selectModel.appendChild(createOption(model))
    }
    selectModel.disabled = false
    const placeholder = document.getElementById('gadget-placeholder')
    if (placeholder) selectGadget.removeChild(placeholder)
  })

  selectModel.addEventListener('change', () => {
    const placeholder = document.getElementById('gadget-placeholder')
    if (placeholder) selectModel.removeChild(placeholder)
  })
}

function createOption(value, text) {
  if (text == undefined) text = value
  let opt = document.createElement('option')
  opt.value = value
  opt.innerHTML = text
  return opt
}
function placeholderOption(type) {
  let opt = createOption('', `Select ${type}`)
  opt.id = `${type}-placeholder`
  return opt
}