這是我第一次使用 javascript,我知道它很糟糕哈哈哈
我正在尋找一種方法來僅顯示 json 中的 currentDateTime 值,T 之后的數字更具體,單擊按鈕時,但每次單擊按鈕時,它都會顯示所有 json 資料。有沒有更好的方法來做到這一點,我的意思是,正確的方法?
<!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>World Clock</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="msg">World Clock</h1>
<p class="dsc">Click one of the buttons to see the current time</p>
<button class="btn1" onclick="estFunc()">Eastern Standard Time (EST)</button>
fetch('http://worldclockapi.com/api/json/est/now')
.then(response => response.json())
.then(data => time = data)
.then(() => console.log(time["currentDateTime"]))
function estFunc() {
const obj = {time};
const estJson = JSON.stringify(obj);
document.getElementById("est").innerHTML = estJson;
}
uj5u.com熱心網友回復:
const estFunc = async () => {
const response = await fetch('http://worldclockapi.com/api/json/est/now', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json(); //extract JSON from the http response
// do something with JSON
document.getElementById("est").innerHTML = data.currentDateTime;
}
<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>World Clock</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="msg">World Clock</h1>
<p class="dsc">Click one of the buttons to see the current time</p>
<button class="btn1" onclick="estFunc()">Eastern Standard Time (EST)</button>
<div id="est"></div>
</body>
</html>
uj5u.com熱心網友回復:
你的意思是重新格式化當前時間并顯示它?你可以參考我下面的代碼。祝你好運! 轉到答案
var stringDate = ("2022-01-17T01:49-05:00").replace(/-/g,"-").replace(/[TZ]/g," ");
var date = new Date(stringDate);
console.log(date.toLocaleTimeString('en-US'));
uj5u.com熱心網友回復:
其他答案沒有錯,但沒有提供錯誤的解釋。您的問題是您stringify從服務器獲得的整個物件,而不僅僅是currentDateTime.
fetch('http://worldclockapi.com/api/json/est/now')
.then(response => response.json())
.then(data => time = data.currentDateTime.time) // only assign currentDateTime.time instead of everything
.then(() => console.log(time.currentDateTime.time))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/417383.html
標籤:
下一篇:決議int和或字串
