首页 > 解决方案 > Facebook Graph API:在 HTML 网页上显示来自控制台的 JSON 数据

问题描述

完全是 Facebook 的 API 和 JavaScript 的新手,所以请多多包涵。

我目前正在尝试:

  1. 使用 Facebook Graph API 检索有关 Facebook 页面事件的数据。使用 JavaScript SDK。
  2. 在其他静态 HTML 网站上插入接下来三个事件的名称、日期和 URL(见下图)

现在的状态是我成功获取了 Facebook 页面事件的 JSON 数据,并且当我运行console.log(response).

但是,作为一个 JS 新手,我怎样才能得到这些数据(最好只用于接下来的三个事件)确实如下图所示显示在我的 HTML 中?

期待看到您的回复!

文本

HTML

window.fbAsyncInit = function() {
    FB.init({
        appId            : 'BLAH',
        autoLogAppEvents : true,
        xfbml            : true,
        version          : 'v10.0'
    });
    FB.api(
        '/BLAH/events?fields=start_time,id,name',
        'GET',
        {access_token:'BLAH BLAH',
        },
        function(response) {
            console.log(response)
        }
    );

};
<a href="#" class="d-inline-flex text-decoration-none align-items-center my-1 hvr-bubble-float-right">
  <div class="arrangement-dato text-white text-center lh-1 d-flex align-items-center flex-column justify-content-center">
      <div class="dato">13</div>
      <div>feb</div>
    </div>
    <h2 class="ms-2 link-dark">Event name</h2>
  </a>
  <a href="#" class="d-inline-flex text-decoration-none align-items-center my-1 hvr-bubble-float-right">
  <div class="arrangement-dato text-white text-center lh-1 d-flex align-items-center flex-column justify-content-center">
    <div class="dato">4</div>
    <div>mar</div>
  </div>
  <h2 class="ms-2 link-dark">Event name</h2>
</a>
<a href="#" class="d-inline-flex text-decoration-none align-items-center my-1 hvr-bubble-float-right">
  <div class="arrangement-dato text-white text-center lh-1 d-flex align-items-center flex-column justify-content-center">
    <div class="dato">12</div>
    <div>apr</div>
  </div>
  <h2 class="ms-2 link-dark">Event name</h2>
</a>

控制台中返回的 JSON 数据示例

id: "1234567890"
name: "Event name"
start_time: "2021-02-20T09:00:00+0100"

PS:我知道我不应该在客户端运行访问令牌。这是我稍后会解决的问题。

PPS:在我的 JS 代码中实际上并没有说“BLAH”。

标签: javascripthtmljson

解决方案


你用的是什么框架?如果你使用纯 JavaScript,你可以这样做:

document.getElementById(<<id of text>>).innerText = response.name;
var date = new Date(response.start_time);

document.getElementById(<<id of green circle>>).innerHTML = date.getDate() + "<br>" + date.getMonth();

如果您使用 jQuery,则将 document.getElementByID() 替换为 $('#' + <>) 并将 innerText 更改为 .text(response.name) 并将 innerHTML 更改为 .html(date.getDate() + "
" + date .getMonth())。

我希望数据是一个数组,然后你必须遍历你的响应对象(搜索循环)。

如果您使用的是 Vue、React 或 Angular,则必须在 Google 上查看如何在此处进行更改。


推荐阅读