为了账号安全,请及时绑定邮箱和手机立即绑定

获取 JSON 并显示 HTML 表

获取 JSON 并显示 HTML 表

蝴蝶不菲 2024-01-18 20:44:08
这就是我正在尝试做的事情。我创建了一个带有表格的 HTML 页面。我定义了除正文标签之外的所有标签。我有一个 javascript,它以 JSON 格式从网络获取数据,对其进行解析,然后使用innerHTML 将元素写入带有标签的表体。如果你让它运行,它就会完美地工作。但是,如果我将此“获取”代码放入函数中并从“提交”按钮的“onclick”执行此函数,则逻辑将停止工作。我在函数的开头放置了一个警报,我可以看到它,但获取部分不起作用。我尝试使用常规函数和异步(等待)。两者都不起作用。这是我的代码(从表单开始)。请让我知道我做错了什么。谢谢。<form enctype="multipart/form-data" action="" method="post">    <button type="submit" name="submit" id="Submit" value="click" onClick = getEarnings()>Click </button></form><table>  <thead>    <tr">        <th>Reported Date</th>        <th>Reported EPS</th>        <th>Estimated EPS</th>        <th>Surprise</th>    </tr>  </thead>  <tbody id="myData"><tbody></table><script>/* function getEarnings() { */    fetch('https://www.alphavantage.co/query?function=EARNINGS&symbol=IBM&apikey=demo')      .then(res => res.text())      .then((out) =>         {            alert("I am here"); // I can't see it if from function            let jsonData = JSON.parse(out);            for (let i = 0; i < jsonData.quarterlyEarnings.length; i++)             {                let earnings = jsonData.quarterlyEarnings[i];                document.getElementById("myData").innerHTML +=                "<tr><td>" + earnings.reportedDate + "</td>" +                "<td align='right'>" + earnings.reportedEPS + "</td>" +                "<td align='right'>" + earnings.estimatedEPS + "</td>" +                "<td align='right'>" + earnings.surprise + "</td></tr>";             };         })      .catch(err => console.error(err));/* } */</script>
查看完整描述

3 回答

?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

您不需要表单来获取数据。我的建议:


getData.onclick = () => {

  fetch('https://www.alphavantage.co/query?function=EARNINGS&symbol=IBM&apikey=demo')

    .then(res => res.text())

    .then((out) => {

      let jsonData = JSON.parse(out);

      for (let i = 0; i < jsonData.quarterlyEarnings.length; i++) {

        let earnings = jsonData.quarterlyEarnings[i];

        myData.innerHTML +=

          "<tr><td>" + earnings.reportedDate + "</td>" +

          "<td align='right'>" + earnings.reportedEPS + "</td>" +

          "<td align='right'>" + earnings.estimatedEPS + "</td>" +

          "<td align='right'>" + earnings.surprise + "</td></tr>";

      };

    })

    .catch(err => console.error(err));

}

<button type="button" id="getData">Get data</button>

<table>

  <thead>

    <tr>

      <th>Reported Date</th>

      <th>Reported EPS</th>

      <th>Estimated EPS</th>

      <th>Surprise</th>

    </tr>

  </thead>

  <tbody id="myData">

    <tbody>

</table>


查看完整回答
反对 回复 2024-01-18
?
UYOU

TA贡献1878条经验 获得超4个赞

当您单击标签中的按钮时,您的页面将刷新,您应该像这样避免这种情况


const getEarnings = (e) => {

// prevent browser from refreshing

e.preventDefault()


fetch()


}


查看完整回答
反对 回复 2024-01-18
?
德玛西亚99

TA贡献1770条经验 获得超3个赞

一些东西:

  1. 使用“onclick”而不是“onClick”(参见底部的注释)

  2. 在引号内设置对 HTML 属性的调用,如下所示:onClick="getEarnings();"

  3. 停止事件传播,因为您的按钮是提交类型并将强制页面重新加载。这可以通过几种方式完成:

    • 您可以将按钮类型设置为“按钮”而不是“提交”,因为后者会强制页面重新加载。

    • 您可以将事件接受到函数中,然后停止事件继续,如下所示:

function getEarnings (e) {

    // This will stop a submit button from reloading the page

    e.preventDefault();

    // Logic here

}

理想情况下,您应该将此逻辑完全放在脚本中,其中您的按钮具有唯一的id,您可以在 DOM 加载时定位并在其上设置事件侦听器。这样您就可以将所有这些移动到一个单独的文件中,并将表示和逻辑分开。在我的脑海中,它会是这样的:


window.addEventListener('DOMContentLoaded', function () {

    const submit = document.getElementById('Submit');

    submit.addEventListener('click', function (e) {

       e.preventDefault();

       // run logic

    });

});

笔记:


查看完整回答
反对 回复 2024-01-18
  • 3 回答
  • 0 关注
  • 48 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信