【问题标题】:How to pass data to d3.json()如何将数据传递给 d3.json()
【发布时间】:2017-09-11 11:48:39
【问题描述】:

目前代码运行良好。只是我想为每个用户提供不同的树形图。所以我必须在 getData.php 中传递 $user 以便根据这个用户然后图表创建 json 数据。 $user 用于getData.php中的mysql select语句从数据库中选择数据,然后将选择的数据转换为json。

请告诉我如何将 $user 作为回调传递给 d3 函数。我没资源了!!

var queryString = window.location.search;
var url = "d3js/getData.php" + queryString;
d3.json(url, function(error, treeData) {
    console.log(treeData)
    root = treeData[0];
    update(root);
});

在getData.php的末尾有

header('Content-Type: application/json');
echo json_encode($tree);

所以我猜php文件的输出是json数据

【问题讨论】:

标签: javascript json d3.js


【解决方案1】:

【讨论】:

  • 这就是语法,如果你有工作 url 那么你必须把绝对 url 放在那个地方
【解决方案2】:

d3.json 函数用于从 json 文件中获取数据,该函数不适用于返回非 json 格式的响应的 PHP 文件。

您可以使用 d3-request API。回电时 - 您可以渲染图表: 示例:

var url = "d3js/getData.php" + window.location.search;
d3.request(url)
.get(function(error, treeData) {
   console.log(treeData)
   root = treeData[0];
   update(root);
});

参考:https://github.com/d3/d3-request/blob/master/README.md#request

更多详情-https://github.com/d3/d3/blob/master/API.md

【讨论】:

  • 1.在您的回调函数中,您可以解析 json 数据。 2. 根据请求类型,调用合适的请求方法(post, get...)
  • 如果 PHP 文件返回 JSON 编码数据,则 d3.json 可以调用 php 文件。反正对我有用。
【解决方案3】:

首先,您需要将数据导出到 json 文件,例如 data.json

d3.json() 需要一个 json 文件而不是 php 文件。

 d3.json("data.json", function(error, data) {
      if (error) throw error;
      ...
});

【讨论】:

  • 我还是觉得需要是你调用的json文件。看看这个问题stackoverflow.com/questions/22325819/d3-js-get-json-from-url
  • 我的代码运行良好。目前我提供 $user=1;在 getData.php 中,它还包含 mysql 代码以获取数据。但由于我的数据将根据用户,我必须将用户数据传递给 getData.php
  • 我知道您的查询获取的是 json,但它会获取 json 文件吗?
  • 是的,就是这样。在 getData.php 的末尾这些是命令: header('Content-Type: application/json'); echo json_encode($tree);
【解决方案4】:

我使用的代码是:

function upL(l_id) {
d3.json("lsel.php?l_id=" + l_id, function(error, gr) {
     if (error) {
        return console.error(error)
    } else
        console.log(gr);
        draw(gr)
}).header("Content-Type", "application/x-www-form-urlencoded")//this bit might be necessary
}

function draw(gr){create graph...}

(l_id 是用户选择的变量)

所以你的看起来没问题,尝试添加内容类型 (.header(...)),如果 treeData 被记录到控制台,问题可能是你访问它的方式。

【讨论】:

    【解决方案5】:

    您还可以使用该函数来获取您的值:

     d3.layout.stack()(['value'].map((value) => {
      return data.map((d: any) => {
        return { x: obj[d.xAxis], y: d.value };
      });
    }));
    

    您还可以在此处查看更多示例-

    https://github.com/amanjain325/angular-d3-charts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2017-04-17
      • 2015-06-21
      • 1970-01-01
      相关资源
      最近更新 更多