[英]Why are these weird functions appearing which I using inner.HTML
I have trying to show the JSON data on the HTML page but weirdly it doesn't show the JSON data but shows this .我试图在 HTML 页面上显示 JSON 数据,但奇怪的是它没有显示 JSON 数据但显示了这个。
The same code works well if the inner.HTML
line is removed and used console.log
instead, this is the output if console.log
is used instead of inner.HTML
.如果删除
inner.HTML
行并改用console.log
,则相同的代码运行良好,如果使用console.log
而不是 inner.HTML ,则这是inner.HTML
。
Code:代码:
pat = $.getJSON("../data/random/anime/pat/pat.json");
function randomObject(obj) {
let arr = Object.values(obj);
content = arr[Math.floor(Math.random() * arr.length)];
document.getElementById("content").innerHTML = content;
}
randomObject(pat);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ASEAN API V2</title>
</head>
<body>
<p id="content"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="./scripts/api.js"></script>
</body>
</html>
The JSON data: JSON 数据:
[
{
"gif": "https://media.discordapp.net/attachments/901270821715210260/901270895446863912/neet-anime.png"
},
{
"gif": "https://tenor.com/view/kanna-kamui-pat-head-pat-gif-12018819"
},
{
"gif": "https://tenor.com/view/pat-head-gakuen-babysitters-kotarou-anime-cute-gif-17907437"
},
{
"gif": "https://tenor.com/view/umaru-frown-happy-feeling-better-pat-gif-10947495"
}
]
You should call randomObject like this: randomObject(pat.responseJSON);
您应该像这样调用 randomObject:
randomObject(pat.responseJSON);
or或者
$.getJSON( "../data/random/anime/pat/pat.json", function( data ) {
randomObject(data);
})
I'm unable to reproduce the same issue you're having, but the only thing I needed to change to get this working was to Stringify the object, so that I had it's content as a plain string.我无法重现您遇到的相同问题,但我唯一需要更改以使其正常工作的是对 object 进行字符串化,以便我将其内容作为纯字符串。
This can then be applied to the HTML element然后可以将其应用于 HTML 元素
function randomObject(obj) {
const arr = Object.values(obj); // Is this necessary? It works fine for me without, since the data is already an array
const randomValue = Math.floor(Math.random() * arr.length); // As a variable to make it clearer what this is for
// "Stringify" (Turn it into a string) first, then we can apply it to the HTML element's content as a plain string
document.getElementById("content").innerHTML = JSON.stringify(arr[randomValue]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.