简体   繁体   English

Js 类名不适用于 fetch json

[英]Js classname doesn't work with fetch json

how is going?怎么样? So I've made this API code here:所以我在这里制作了这个 API 代码:

index.php index.php

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){
    // API Endpoint
    var x = document.getElementsByClassName("name1");
    var y = document.getElementsByClassName("name2");
    var i;
    var url = 'mysite.org/api.php'
    // Fetch the remote file
    fetch(url)
    .then(function (request) {
        // Take the request and parse the data as json
        return request.json()
    })
    .then(function (json) {
      // line1
      var name1 = json.item1.name // current song title
      x.innerHTML = name;
      // line2
      var name2 = json.item2.name // current song title
      y.innerHTML = name2;
    });
  });
  </script>
</head>
<body>
  <h5>Hello</h5>
  <div class="name1"></div>
  <div class="name2"></div>
</body>
</html>

api.php ((the json is generated by array from a cicle while )) api.php ((( json是由数组从循环中生成的,))

{"item1":{"id":"1","name":"Daniel"},"item2":{"id":"2","name":"Kalifa"}}

So this code works fine and I can see item1 inside div id name1 and item2 inside div id name2 .所以这段代码工作正常,我可以在div id name1中看到item1和在div id name2中看到item2 But I dunno why but when I try to change the elements from ID to CLASS it doesn't work.但我不知道为什么,但是当我尝试将元素从ID更改为CLASS时,它不起作用。 Any ideas?有任何想法吗?

Loop over the object keys in the JSON, get the element with the same class, and assign its innerHTML .循环遍历 JSON 中的 object 键,获取具有相同 class 的元素,并分配其innerHTML

Object.entries(json).forEach(([name, value]) => 
    document.getElementsByClassName(name)[0].innerHTML = value);

When you use getElementsByClassName() you need to index it to get the first element with that class.当您使用getElementsByClassName()时,您需要对其进行索引以获取具有该 class 的第一个元素。

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

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