I'm trying to create a div with news articles and need my div to send the user to the new page referenced by the provided link from my JSON file. My issue is how can I properly reference the link from the JSON file, so when the json file updates, so does the directory. (I'm still learning JS at the moment).
JSON file:
{
"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>
If I were to change response67.AUD[0].link;
to the actual link, then it works fine. Although it's not in my best interest to keep manually typing every single link for all news articles (there's a lot, this is just a snippet).
JS can't work directly with a JSON. You have to parse the JSON to an JS Object/Array by using the JSON.parse()
function.
you could change your line:
var newLoc = response67.AUD[0].link;
to this:
var object = JSON.parse(response67);
var newLoc = object.AUD[0].link;
let response = `{ "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/" }] }`; response = JSON.parse(response); console.log(response.AUD[0].link);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.