javascript 从数据库动态加载外部数据到 d3.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12519209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:25:42  来源:igfitidea点击:

Dynamically loading external data from database into d3.js

javascriptjqueryd3.js

提问by Jeremy Wilson

I am trying to get dynamic reloading to work in d3 and I'm having trouble trying to figure out how to refresh the data from the database.

我正在尝试动态重新加载以在 d3 中工作,但在尝试弄清楚如何刷新数据库中的数据时遇到了麻烦。

I have an array that contains values should change every second:

我有一个数组,其中包含的值应该每秒更改一次:

var data = [1,2,3,4];

var 数据 = [1,2,3,4];

In my initial script, I had PHP pull the data from the database to set up the array, and reloading the page works fine for that, but I'd like to use d3's reload functionality to fetch new data and redraw the diagram.

在我的初始脚本中,我让 PHP 从数据库中提取数据来设置数组,然后重新加载页面就可以了,但我想使用 d3 的重新加载功能来获取新数据并重新绘制图表。

I'm completely new to js and d3, so any suggestions would be very helpful.

我对 js 和 d3 完全陌生,所以任何建议都会非常有帮助。

I tried using jQuery's get command to call an external PHP script that outputs the values but that doesn't seem to work.

我尝试使用 jQuery 的 get 命令调用输出值的外部 PHP 脚本,但这似乎不起作用。

I'm basically trying to replicate the bar chart from Google Analytics real time display.

我基本上是在尝试从 Google Analytics 实时显示中复制条形图。

回答by Y?co

This might help you: https://github.com/d3/d3-request/blob/master/README.md#request

这可能对您有所帮助:https: //github.com/d3/d3-request/blob/master/README.md#request

Edit: updated link to API v4

编辑:更新的 API v4 链接

回答by logical Chimp

firstly, you need a page on the server that will output the data in JSON format*. Once you have that page, call it from the browser, and you should get the encoded data appearing on screen (this will prove that the page is hosted properly and returning data)

首先,您需要在服务器上有一个页面,该页面将以 JSON 格式* 输出数据。一旦你有了那个页面,从浏览器调用它,你应该让编码数据出现在屏幕上(这将证明页面被正确托管并返回数据)

Next, follow the simple example on the D3 docs link that Yeco posted. You'll need to replace the dummy URL with the address to your new data page, and stick your own function call in there to redraw the chart with the new data.

接下来,按照 Yeco 发布的 D3 文档链接上的简单示例进行操作。您需要将虚拟 URL 替换为新数据页面的地址,并将您自己的函数调用粘贴到其中以使用新数据重新绘制图表。

*Note: I am not familiar with PHP, but it should have either a native JSON encoder, or a library will be available on the net. You'll also need to make sure you set the response mime type appropriately - a quick google should give you the correct mime type - it's something like 'application/json' I think, but can't remember of the top of my head

*注意:我不熟悉 PHP,但它应该具有本机 JSON 编码器,或者网络上有可用的库。您还需要确保正确设置响应 mime 类型 - 一个快速的谷歌应该为您提供正确的 mime 类型 - 我认为它类似于“application/json”,但不记得我的头顶