通过Google AnalyticsAPI显示单个数据字段

时间:2017-06-02 16:10:23

标签: javascript google-analytics google-analytics-api

我无法通过Google AnalyticsAPI仅显示单个数据字段。

例如,我如何显示昨天的用户数量?或者过去一周的用户数量?

我假设“gapi.analytics.report.Data”是正确的构造函数。我已尝试按照Google内置组件参考中的“数据”代码进行操作,但前端没有显示任何内容。

对于“DataChart”代码,有一个“容器”选项,它引用DOM中正确显示图表的HTML元素。

“数据”中缺少此“容器”选项 - 因此如何显示单个数据字段?

编辑:这是我正在使用的代码。

您可以在此处查看我的代码的粘贴框:https://pastebin.com/M6U0Bd8B

此处还有网站的实时暂存版本:http://madebychris.ca/dashboard2.html

前四个section id都显示正常但没有显示最终<p class ="report">

1 个答案:

答案 0 :(得分:0)

如果您尝试访问原始数据编号,则只需访问响应对象:

// Set up the request
var report = new gapi.analytics.report.Data({
  query: {
    ids: 'ga:XXXX',
    metrics: 'ga:sessions',
    dimensions: 'ga:city'
  }
});

// Define what to do with the response data.
report.on('success', function(response) {
  console.log(response);
});

// Run the report
report.execute();

例如,指标的总计为response.totalsForAllResults,每个维度的行都保存在response.rows

您需要选择要对report.on("success", function(response){函数上的变量执行的操作。例如:

report.on('success', function(response) {
$("body > main > div > section:nth-child(4) > h2")[0].innerText = 
   response.totalsForAllResults["ga:sessions"]
});

report.execute();

注意:您应该可以在embedded API demo上进行测试。使用console.log复制和粘贴初始代码应该有助于显示正在发生的事情。