我正在开发一个使用 yii2 的应用程序,我想集成 miloschuman 图表扩展
我默认使用
echo Highcharts::widget([
'scripts' => [
'modules/exporting',
'themes/grid-light',
],
'options' => [
'title' => [
'text' => 'Trucks chart',
],
'xAxis' => [
'categories' => ['Apples', 'Oranges', 'Pears', 'Bananas', 'Plums'],
],
'labels' => [
'items' => [
[
'html' => 'Total fruit consumption',
'style' => [
'left' => '50px',
'top' => '18px',
'color' => new JsExpression('(Highcharts.theme && Highcharts.theme.textColor) || "black"'),
],
],
],
],
'series' => [
[
'type' => 'column',
'name' => 'Rejected trucks',
'data' => [3, 2, 1, 3, 4],
],
[
'type' => 'column',
'name' => 'Approved trucks',
'data' => [2, 3, 5, 7, 6],
],
[
'type' => 'column',
'name' => 'Joe',
'data' => [4, 3, 3, 9, 0],
],
/*[
'type' => 'spline',
'name' => 'Average',
'data' => [3, 2.67, 3, 6.33, 3.33],
'marker' => [
'lineWidth' => 2,
'lineColor' => new JsExpression('Highcharts.getOptions().colors[3]'),
'fillColor' => 'white',
],
],*/
[
'type' => 'pie',
'name' => 'Total trucks in pie chart',
'data' => [
[
'name' => 'Jane',
'y' => 13,
'color' => new JsExpression('Highcharts.getOptions().colors[0]'), // Jane's color
],
[
'name' => 'John',
'y' => 23,
'color' => new JsExpression('Highcharts.getOptions().colors[1]'), // John's color
],
[
'name' => 'Joe',
'y' => 19,
'color' => new JsExpression('Highcharts.getOptions().colors[2]'), // Joe's color
],
],
'center' => [100, 80],
'size' => 100,
'showInLegend' => false,
'dataLabels' => [
'enabled' => false,
],
],
],
]
]);
这会很好地呈现数据,但我想使用自定义 javascript 函数获取数据,每 5 秒刷新一次数据。我该怎么做
我有一个自定义函数
$this->registerJs('$.getJSON("//www.highcharts.com/samples/data/
jsonp.php?filename=aapl-c.json&callback=?",
myCallbackFunction);');
我如何更改系列中的数据以使用返回 json 的 ajax 函数
我检查过:this link但它不是很有帮助,有人可以指导我前进的道路,或者可能是其他扩展实现了 ajax 请求中来自服务器的数据的 yii2 图表
最佳答案
您的问题并没有透露您愿意自己进行多少试验和错误,或者您是否正在为所需的每个更改寻找完整代码。如果您正在寻找细节而不是有关所需更改的指导,请告诉我。
希望这能让你到达你想去的地方:
- 将数据创建(代码中数组的系列部分)移动到相关模型中的方法(静态或其他)。
例如,如果您要处理卡车,那么您可以创建 public static function getChartData(){
,然后创建 Truck::getChartData()
该方法将返回一个 php 数组。例如:
[
'类型'=>'列',
'name' => '拒绝卡车',
'数据'=> [3, 2, 1, 3, 4],
],
[
'类型'=>'列',
'name' => '认可的卡车',
'数据'=> [2, 3, 5, 7, 6],
],
这可以包含在上面的现有代码中,或者使用 JSON::encode()
或类似的方法进行转换,以便在使用 ajax 请求时每 5 秒返回一次。
- 在上面的代码中使用您的新方法。所以:
'series' => Truck::getChartData()
- 让图表每 5 秒请求更新一次数据。
您链接到的页面有一个示例,该示例在图表的加载事件上触发并每 5 秒发送一次 ajax 请求。它似乎只更新第一个系列 [0]
但可以轻松更新以切换所有系列。除非有一些不适合您的具体内容,否则这应该会很好。
- 您需要在配置中创建一个新路由以将上述 ajax 请求发送到,然后在相关 Controller 中创建一个新操作,该操作从
Truck::getChartData()
返回 json 编码的响应,以便该方法被重复使用。
关于javascript - 每次在 yii2 中使用带有 ajax 刷新的图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39924705/