这是console.log('<?php print_r($graph) ?>');
{"H10":"98.25","I10":"59.00","H17":"59.26","I17":"26.10","H22":"0.00","I22":"1.84","H40":"0.00","I40":"0.00","H2":"14.88","I2":"8.80" }
我想通过java脚本中的键获取这些值,如何逐个获取这些值?
我试过了
console.log('<?php print_r($graph['H10']) ?>');
但它无效
答案 0 :(得分:0)
你在JavaScript中说过&#34;&#34;但你尝试这样做是在PHP。请记住,PHP在服务器上运行,并确定发送到浏览器的内容; JavaScript代码(在本例中)在浏览器中的客户端上运行。
如果您想在JavaScript中访问此数据,请先将其作为数据输出到您的JavaScript代码中。
不清楚PHP代码中包含的$graph
,字符串或关联数组。
如果它是一个关联数组,请使用json_encode
和echo
:
var data = <?php echo(json_encode($graph)); ?>;
但是,我怀疑它是一个JSON格式的字符串,基于你试过的东西没有给你"98.25"
;在这种情况下,只需回应它:
var data = <?php echo($graph); ?>;
其中一个会将此信息发送到浏览器:
var data = {"H10":"98.25","I10":"59.00","H17":"59.26","I17":"26.10","H22":"0.00","I22":"1.84","H40":"0.00","I40":"0.00","H2":"14.88","I2":"8.80"};
然后,在浏览器上的JavaScript代码中,您有一个对象,其属性名称为H10
等等:
console.log(data.H10);
// or
console.log(data["H10"]);
实例:
var data = {"H10":"98.25","I10":"59.00","H17":"59.26","I17":"26.10","H22":"0.00","I22":"1.84","H40":"0.00","I40":"0.00","H2":"14.88","I2":"8.80"};
console.log(data.H10);
// or
console.log(data["H10"]);
&#13;
如果要遍历所有属性,可以使用Object.keys
获取属性名称数组,并循环遍历它们:
Object.keys(data).forEach(function(name) {
console.log(name + " = " + data[name]);
});
实例:
var data = {"H10":"98.25","I10":"59.00","H17":"59.26","I17":"26.10","H22":"0.00","I22":"1.84","H40":"0.00","I40":"0.00","H2":"14.88","I2":"8.80"};
Object.keys(data).forEach(function(name) {
console.log(name + " = " + data[name]);
});
&#13;