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

时间:2019-02-19 21:14:07

标签: javascript html json

我有一个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>

3 个答案:

答案 0 :(得分:1)

使用fetch API加载json文件。

"link"

我建议使用名为lit-html的轻量级模板库来构建DOM。

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Fetching the link from the Intent.
    String link = getIntent().getStringExtra("link");

    // .. display the link

您还可以考虑为下拉菜单定义一个自定义元素,该元素将使用占位符属性来定义该字符串,并将字符串选项数组作为属性。不过请注意,由于Form Participation API尚未准备就绪,目前您必须使用javascript访问select的值。

working stackblitz

const handleAsJson = response => response.json();
const handleError = console.error // or some such;
fetch('/url/to/file.json')
  .then(handleAsJson)
  .catch(handleError);

答案 1 :(得分:0)

输入您的代码

    <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>

您可以使用XMLHttpRequest对象发送AJAX请求,从服务器获取数据后,可以使用遍历JSON数据的方式将选项附加到select元素。

HTML

<select id="abc">
</select>

JS

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
   var data = xhttp.responseJSON;
   for(var i in data){
       var op = document.createElement('option');
       op.text=data[i].text;
       op.value=data[i].value;
       document.getElementById('abc').appendChild(op);
   }
  }
};
xhttp.open("GET", "filename", true);
xhttp.send();

您的数据将像[{"text":"abc","value":"abc"},{.......]

答案 2 :(得分:0)

HTML:

<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
}