gpt4 book ai didi

javascript - 将 php 变量传递给 morris.js

转载 作者:行者123 更新时间:2023-12-02 17:44:21 25 4
gpt4 key购买 nike

嗨,我在 javascript 方面有相当的经验,但我陷入了以下情况。
我正在开发一个 PHP 页面来在图表中显示一些值。我正在使用 morris.js。

现在 morris.js 使用以下格式的数组来显示为图表:

// AREA CHART
var area = new Morris.Area({
element: 'revenue-chart',
resize: true,
data: [
{y: '2011', purchase: 500, sale: 1000, profit: 500},
{y: '2012', purchase: 600, sale: 1100, profit: 500},
{y: '2013', purchase: 500, sale: 1050, profit: 550}
],
xkey: 'y',
ykeys: ['profit', 'purchase', 'sale'],
labels: ['Profit', 'Purchase', 'Sale'],
lineColors: ['#a0d0e0', '#3c8dbc', '#ac5bc3'],
hideHover: 'auto'
});

但是我在 php 变量中有这些值,例如:

$year1 = '2011';
$sale1 = '1000';
$purchase1 = '500';
$profit1 = '500';

$year2 = '2012';
$sale2 = '1200';
$purchase2 = '600';
$profit2 = '500';

$year3 = '2013';
$sale3 = '1050';
$purchase3 = '500';
$profit3 = '550';

如何将这些 php 值传递给 js。我尝试了 json_encode() 但它对我不起作用。

更新:用 Luke Cordingley 的答案显示更新的代码,仍然有问题。

        <script type="text/javascript">
window.MyProjectNamespace.phpVars = <?
$phpVars = array('year' => '2011', 'purchase' => '1000', 'sale' => '600', 'profit' => '400');
echo json_encode($phpVars);
?>
</script>

<script type="text/javascript">
$(function() {

// AREA CHART
var area = new Morris.Area({
element: 'revenue-chart',
resize: true,
data: [
{y: window.MyProjectNamespace.phpVars.year, purchase: "500", sale: "1000", profit: "500"},
{y: "2012", purchase: "600", sale: "1100", profit: "500"},
{y: "2013", purchase: "500", sale: "1050", profit: "550"}
],
xkey: 'y',
ykeys: ['profit', 'purchase', 'sale'],
labels: ['Profit', 'Purchase', 'Sale'],
lineColors: ['#a0d0e0', '#3c8dbc', '#000000'],
hideHover: 'auto'
});
});

最佳答案

您需要动态生成 JavaScript,或者按照我的喜好,创建一个与我的 PHP 变量相对应的 JavaScript 对象。将 PHP 变量放入 JavaScript 后,只需根据需要将它们传递给任何 JavaScript 方法即可。以下是如何在 JavaScript 中获取 PHP 变量的示例:

<script type="text/javascript">
$(function() {
window.MyProjectNamespace = {};
window.MyProjectNamespace.phpVars = <?php
$phpVars = array('year' => '2011', 'purchase' => '1000', 'sale' => '600', 'profit' => '400');
echo json_encode($phpVars);
?>;

// AREA CHART
var area = new Morris.Area({
element: 'revenue-chart',
resize: true,
data: [
{y: window.MyProjectNamespace.phpVars.year, purchase: "500", sale: "1000", profit: "500"},
{y: "2012", purchase: "600", sale: "1100", profit: "500"},
{y: "2013", purchase: "500", sale: "1050", profit: "550"}
],
xkey: 'y',
ykeys: ['profit', 'purchase', 'sale'],
labels: ['Profit', 'Purchase', 'Sale'],
lineColors: ['#a0d0e0', '#3c8dbc', '#000000'],
hideHover: 'auto'
});
});
</script>

关于javascript - 将 php 变量传递给 morris.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21894941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com