javascript 如何只获取特定的JSON数据

0kjbasz6  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(104)

这是我第一次使用JavaScript,我知道它很糟糕哈哈哈!
我正在寻找一种方法来显示只currentDateTime值从JSON,数字后的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>

个字符

2ledvvac

2ledvvac1#

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;
}

个字符

jxct1oxe

jxct1oxe2#

其他的答案都没有错,但没有解释错在哪里。您的问题是您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))

字符串

相关问题