如何在java脚本函数中传递值。如果我有类似下面的价值?
我有一些像这样的PHP值
<?php $dataset = "{"label":"Server","value" : "40"},{"label":"Hypervisor","value" : "40"},{"label":"AD","value" : "40"},{"label":"vCenter - permissions","value" : "40"},{"label":"vCenter - maintenance","value" : "40"},{"label":"Resource Pool/datastore migration","value" : "40"},{"label":"vm - reboot","value" : "40"},{"label":"test1","value" : "40"},{"label":"VM","value" : "40"},{"label":"test3","value" : "40"},{"label":"Host modification","value" : "40"},{"label":"Host test","value" : "40"},{"label":"vCenter - Resource Pool (RP) modification","value" : "40"},{"label":"test 2","value" : "40"},{"label":"test 3","value" : "40"}"; ?>
我正在尝试在javascript函数中传递此值,但我得到错误?我怎么能解决这个问题?
function somthing(<?php echo $dataset ?>){
}
未捕获的SyntaxError:意外的令牌,
答案 0 :(得分:1)
首先你的数据定义是错误的,因为javscript中有多个对象需要在[{},{},...]
中包装才能生成有效的javascript。
我认为将数据集数据加载到单独的javascript变量中会更容易,也可能更灵活。我也分别回应了每一行,因为我认为更容易阅读/调试
然后从那里很容易,我缩短了dataset
以便更容易阅读答案而不会消除任何复杂性(或者我相信)
$dataset = '[{"label":"Server","value" : "40"},{"label":"Hypervisor","value" : "40"}]';
echo '<script type="text/javascript">';
echo "var dataset = $dataset;";
echo 'function somthing(dataset){';
echo '}';
echo '</script>';
我想假设您使用$dataset
创建json_encode($someArray)
,但在这种情况下,它不会出错。
我是否可以建议您查看json_encode()和json_decode()
的手册页