变量不从 PHP 传递到 javascript

Variable not passing from PHP to javascript

本文关键字:javascript PHP 变量      更新时间:2023-09-26

我已经阅读了这里几乎所有的问题,试图获取从PHP传递到javascript的数值。如您所见,我成功生成了随机数并且效果很好,但是当我尝试将变量传递给 graph.update 函数时,即使两个变量都有根据 firebug 的值(分别为 14060116 和 0,这是正确的),它们也没有进入更新函数......有什么想法吗?如果有帮助,这是完整的脚本!

<script>
(function () {
    function createCanvas(divName) {
        var div = document.getElementById(divName);
        var canvas = document.createElement('canvas');
        div.appendChild(canvas);
        if (typeof G_vmlCanvasManager != 'undefined') {
            canvas = G_vmlCanvasManager.initElement(canvas);
        }   
        var ctx = canvas.getContext("2d");
        return ctx;
    }
    var ctx = createCanvas("graphDiv1");
    var upld = <?php echo json_encode($dirupld[0]); ?>;
    var upldred = <?php echo json_encode($dirupldred[0]); ?>;
    var graph = new BarGraph(ctx);
    graph.maxValue = 30;
    graph.margin = 10;
    graph.width = 450;
    graph.height = 200;
    graph.colors = ["#49a0d8", "#d353a0"];
    graph.xAxisLabelArr = ["Traditional", "Duplicate Reduced"];
    graph.update([upld, upldred]);
    //graph.update([Math.random() * 30, Math.random() * 30]);
}());
</script>

不确定我在哪里丢失了值?Firebug 报告以下内容

var upld = 14060116;
var upldred = 0;
graph.update([upld, upldred]); 
First you will passing hidden values in php form
something like this
<input type="hidden" name="upld" id="upld" value="<?php echo json_encode($dirupld[0]); ?>">
<input type="hidden" name="upldred" id="upldred" value=" <?php echo json_encode($dirupldred[0]); ?>">
then you will get this value in javascript
var upld=document.getElementById("upld").value;
var upldred=document.getElementById("upldred").value;
dont use below the code
 var upld = <?php echo json_encode($dirupld[0]); ?>; //Is not Correct
    var upldred = <?php echo json_encode($dirupldred[0]); ?>;//Is not correct
Use document.getElementById().value syntax

请尝试更改 graph.maxValue 的值以显示 upld

我假设您不希望为 upldred 显示任何内容,因为它已经是 0

你的PHP看起来很合理;你从PHP得到整数,然后将这些整数作为参数传递来呈现条形图。正如其他人所提到的,它出现的事实意味着你的PHP很好,这是一个JS问题。

但是由于您设置了graph.maxValue = 30;因此当您尝试呈现值为 14060116 的图表时会出现错误:

Uncaught IndexSizeError: Index or size was negative, or greater than the allowed value.

(我假设您正在使用 http://www.williammalone.com/articles/html5-canvas-javascript-bar-graph/)