【发布时间】:2021-06-21 16:51:51
【问题描述】:
最近怎么样? 所以我在这里制作了这个 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>
api.php((json由array从循环while生成))
{"item1":{"id":"1","name":"Daniel"},"item2":{"id":"2","name":"Kalifa"}}
所以这段代码工作正常,我可以在 div id name1 中看到 item1 和 div id name2 中的 item2 >。但我不知道为什么,但是当我尝试将元素从 ID 更改为 CLASS 时,它不起作用。 有什么想法吗?
【问题讨论】:
-
你能告诉我们不工作的代码吗?
-
我敢打赌这是问题所在:stackoverflow.com/questions/10693845/…
-
“它不起作用” 不是问题描述。描述会发生什么,您预计会发生什么,并包含您看到的任何错误消息的完整文本。
-
@Axel10
getElementsByClassName不返回单个元素。它与getElementById不同。看看@Barmar 发布的链接。 -
var x = document.getElementsByClassName("name1")[0]
标签: javascript php html json