javascript 显示 "而不是双引号

时间:2021-07-06 15:16:46

标签: javascript php laravel charts

我想通过 javascript 在我的页面中显示折线图。 显示图表的示例代码如下

new Chartist.Line('#chart-with-area', {
  labels: ["d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8"],
  series: [
    [5, 9, 7, 8, 5, 3, 5, 4]
  ]
}, {
  low: 0,
  showArea: true,
  plugins: [
    Chartist.plugins.tooltip()
  ]
});

我正在使用 Laravel 框架,我需要将数据从 php 发送到 javascript。

我创建了两个数组,一个用于标签,一个用于数据。

问题是当我为标签添加数组时,我遇到了以下错误

htmlspecialchars(): 参数 #1 ($string) 必须是字符串类型,给定数组

当我发送 json 时,javascript 更改双引号

new Chartist.Line('#chart-with-area', {
                labels: ["2021\/7\/5","2018\/11\/17","2019\/1\/8","2018\/10\/25","2019\/4\/9","2018\/11\/18","2019\/3\/11","2019\/1\/3","2019\/1\/5","2018\/12\/17","2021\/5\/25","2018\/12\/31"],
                series: [[1,1,1,1,1,1,1,3,1,1,2,6]]
            }, {
                low: 0,
                showArea: true,
                plugins: [
                    Chartist.plugins.tooltip()
                ]
            });

这是我的代码:

new Chartist.Line('#chart-with-area', {
            labels: {{json_encode($requestLineChartLabel)}},
            series: [{{json_encode($requestLineChartData,JSON_NUMERIC_CHECK)}}]
        }, {
            low: 0,
            showArea: true,
            plugins: [
                Chartist.plugins.tooltip()
            ]
        });

我搜索了很多,但找不到任何解决方案。

1 个答案:

答案 0 :(得分:2)

如果您使用的是 Laravel 7 或更高版本,则可以使用 @json 刀片指令正确输出 json:

labels: @json($requestLineChartLabel),
series: [@json($requestLineChartData,JSON_NUMERIC_CHECK)]

只要确保这些变量不是 json,否则你将对其进行双重编码。

相关问题