Javascript Js classname不';无法使用fetchjson

Javascript Js classname不';无法使用fetchjson,javascript,php,html,json,Javascript,Php,Html,Json,进展如何? 我在这里编写了以下API代码: 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> $(do

进展如何? 我在这里编写了以下API代码:

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>
因此,该代码工作正常,我可以在div id name1中看到item1item2中看到div id name2。但我不知道为什么,但当我尝试将元素从ID更改为CLASS时,它不起作用。
有什么想法吗?

在JSON中循环对象键,获取具有相同类的元素,并分配其
innerHTML

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

当您使用
GetElementsByCassName()
时,您需要对其进行索引,以获取该类的第一个元素。

您可以向我们展示不起作用的代码吗?我敢打赌这就是问题所在:“它不起作用”不是问题描述。描述发生了什么,预期会发生什么,并包括您看到的任何错误消息的完整文本。@Axel10
getElementsByClassName
不返回单个元素。它与
getElementById
不同。看看@Barmar发布的链接。
var x=document.getElementsByClassName(“name1”)[0]
谢谢你!!:)
Object.entries(json).forEach(([name, value]) => 
    document.getElementsByClassName(name)[0].innerHTML = value);