【发布时间】:2022-12-31 21:26:57
【问题描述】:
我正在尝试创建一个包含新闻文章的 div,并且需要我的 div 将用户发送到由我的 JSON 文件中提供的链接引用的新页面。我的问题是如何正确引用 JSON 文件中的链接,因此当 json 文件更新时,目录也会更新。 (我现在还在学习 JS)。
JSON 文件:
{
"AUD": [
{
"title": "Pound Australian Dollar Exchange Rate News: GBP/AUD Rallies on Risk-Averse Market",
"media": "TorFX News",
"date": "7 mins ago",
"link": "https://news.torfx.com/post/2022-12-29_pound-australian-dollar-exchange-rate-news-gbp-aud-rallies-on-risk-averse-market/"
}
]
}
HTML 和 JS:
<!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">
<!----======== CSS ======== -->
<link rel="stylesheet" href="style.css">
<link href='https://unpkg.com/boxicons@2.1.1/css/boxicons.min.css' rel='stylesheet'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" charset="UTF-8"></script>
</head>
<body>
<div class="forex_news_container1">
<div class="forex_news_containerAUD fxcontentNEWS">
<div class="yooo" onclick="setCurrentLocation()" style="cursor: pointer;">
send_to_new_page
</div>
<script>
const requestUrl67 = 'https://api.npoint.io/b4841826d7668f639d10';
const requestJSON67 = async url => {
const response67 = await (await fetch(url)).json();
function setCurrentLocation() {
var newloc = response67.AUD[0].link;
window.location.href = newloc;
}
}
requestJSON67(requestUrl67);
</script>
</div>
</div>
如果我将response67.AUD[0].link; 更改为实际链接,那么它就可以正常工作。尽管手动输入所有新闻文章的每个链接并不符合我的最佳利益(有很多,这只是一个 sn-p)。
【问题讨论】:
-
您需要将 JSON 解析为对象才能在 JS 中使用它 (
parse()) -
很酷,我必须在哪里包括它?在宣布“Response67”之后?
标签: javascript html json