2013-10-03 118 views
0

我已经通读了几乎所有关于试图获取从PHP传递到javascript的数值的问题。正如你所看到的,我成功生成了随机数并且效果很好,但是当我试图将变量传递给graph.update函数时,即使两个变量的值都根据萤火虫(分别为14060116和0,这是正确的)他们没有把它更新到更新功能......任何想法?这是完整的脚本,如果它有帮助!变量不能从PHP传递到javascript

<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> 

不知道我失去了价值?萤火虫是报告以下

var upld = 14060116; 
var upldred = 0; 
graph.update([upld, upldred]); 
+0

做尝试把它们放在''“' – Deepak

+0

如果你可以看到Firebug的变量,那不是纯粹的JavaScript问题吗? :) –

+0

可以提供'json_encode($ dirupldred [0]);'从PHP脚本的示例输出?它看起来像'upld'获得一个整数,而不是JSON对象。 'upldred'也一样 –

回答

0
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 
+0

我确切地看到你在那里做了什么,感谢一吨,它完美的工作!将此添加到长期记忆中,因为我保证我会在别处也需要它。 – Braden

0

尝试改变graph.maxValue的价值得到upld显示

我假设你没有想到什么显示为upldred,因为它已经是0

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/

+0

找出其中一个答案,我完全错过了最大值部分。之前使用它进行调试,当我解决变量问题时,可能会花费我一分钟的困惑! – Braden