json 我希望使用我的私有API获取数据,但我希望它们是复选框

gijlo24d  于 2023-01-27  发布在  其他
关注(0)|答案(2)|浏览(109)


这是我目前掌握的情况
main.html(顺便说一句,这是一个表单)

<div class="form-group form-check-inline">
     <input class="form-check-input" type="radio" name="region" id="US" value="US">
     <label class="form-check-label" for="US">US</label>
</div>

api.js

document.addEventListener('DOMContentLoaded', () => {
const urlUS = new URL("http://127.0.0.1:3000/api/v1/regionApi/regionProduct/1")
document.getElementById('US').addEventListener('click', getRegionUS)

function getRegionUS() {
        fetch(urlUS, {
            method:'GET'
        })
            .then(res => res.json())
            .then(data => {
                data.forEach(function(product){
                    output = `
                    <div class="form-group form-check">
                    <input class="form-check-input" type="checkbox" value="${product.productname}" id="${product.id}">
                    <label class="form-check-label" for="${product.id}">
                    ${product.productname}
                    </label>
                    </div>
                    `
                })
                
                document.getElementById('US').innerHTML = output
                console.log(data)
            })
            .catch(error => console.log('error'))
    }

})

当我点击单选按钮时,我确实得到了我在API中寻找的信息。我错过了什么?为什么它没有出现在复选框中?我应该尝试什么?

zfciruhq

zfciruhq1#

你的代码似乎有一些问题...
1.您正在替换foreach外部的HTML,但它只使用对output的最后一次赋值,因为每次迭代都会覆盖它。
1.您正试图将HTML***添加到***复选框输入元素中,这是不允许的。
你需要构建HTML,每次迭代都添加到HTML中,然后再将其全部插入到页面中。你还需要在页面上的其他地方添加生成的HTML。见下文

  • 请注意:我使用了一个免费提供的JSON API,专门用于提供伪测试数据,因此我不得不稍微更改HTML生成以处理该数据 *
document.addEventListener('DOMContentLoaded', () => {
  const urlUS = new URL("https://jsonplaceholder.typicode.com/users")
  document.getElementById('US').addEventListener('click', getRegionUS)

  function getRegionUS() {
    fetch(urlUS, { method: 'GET' })
      .then(res => res.json())
      .then(data => {
        let output = '';

        data.forEach(function(product) {
          output += `
                    <div class="form-group form-check">
                    <input class="form-check-input" type="checkbox" value="${product.name}" id="${product.id}">
                    <label class="form-check-label" for="${product.id}">
                    ${product.name}
                    </label>
                    </div>
                    `;
        })

        document.getElementById('productInfo').innerHTML = output;
        // console.log(data)
      })
      .catch(error => console.log('error'))
  }
})
<div class="form-group form-check-inline">
  <input class="form-check-input" type="radio" name="region" id="US" value="US">
  <label class="form-check-label" for="US">US</label>
</div>

<div id="productInfo">Generated HTML will appear here!</div>
yrwegjxp

yrwegjxp2#

这可以更优雅和简洁-我在这里从容器进行委托
注意我重用了另一个答案中的JSON模拟数据url。更改product.whatever以匹配您的对象

const regions = {
  "US": 1,
  "EUR": 2
};
const url = 'https://jsonplaceholder.typicode.com/posts?userId=';

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById('item-carousel').addEventListener('click', (e) => {
    const tgt = e.target;
    fetch(`${url}${regions[tgt.id]}`, { method: 'GET' })
      .then(res => res.json())
      .then(data => {
        document.getElementById('productInfo').innerHTML = data.map(product => `<div class="form-group form-check">
                    <input class="form-check-input" type="checkbox" value="${product.title}" id="${product.id}">
                    <label class="form-check-label" for="${product.id}">${product.body}</label>
                    </div>`).join('');
      });
  });
});
<div id="item-carousel">
  <div class="form-group form-check-inline">
    <input class="form-check-input" type="radio" name="region" id="US" value="US">
    <label class="form-check-label" for="US">US</label>
  </div>
  <div class="form-group form-check-inline">
    <input class="form-check-input" type="radio" name="region" id="EUR" value="EUR">
    <label class="form-check-label" for="EUR">EUR</label>
  </div>
</div>
<div id="productInfo">Generated HTML will appear here!</div>

相关问题