将PHP数组传递给JavaScript函数我正在尝试将PHP数组变量转换为JavaScript变量。这是我的密码:<html>
<head>
<script type="text/javascript">
function drawChart(row,day,week,month,date)
{
// Some code...
}
</script>
</head>
<body>
<?php for($counter = 0; $counter<count($au); $counter++)
{
switch($au[$counter]->id)
{
case pageID.'/insights/page_active_users/day':
$day[] = $au[$counter]->value;
break;
case pageID.'/insights/page_active_users/week':
$week[] = $au[$counter]->value;
break;
case pageID.'/insights/page_active_users/month':
$month[] = $au[$counter]->value;
break;
}
}
?>
<script>
drawChart(600/50, '<?php echo $day; ?>', '<?php echo $week; ?>', '<?php echo $month; ?>',
'<?php echo createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')),
date('Y',strtotime('-1 day')))); ?>');
</script>
</body></html>我无法获得PHP数组的值。我该如何解决这个问题?
3 回答
慕仙森
TA贡献1827条经验 获得超7个赞
$php_variable
<script type="text/javascript"> var obj = <?php echo json_encode($php_variable); ?>;</script>
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
JSON.parse(..)
var s = "<JSON-String>";var obj = JSON.parse(s);
侃侃无极
TA贡献2051条经验 获得超10个赞
json_encode
<?php $phpArray = array( 0 => "Mon", 1 => "Tue", 2 => "Wed", 3 => "Thu", 4 => "Fri", 5 => "Sat", 6 => "Sun", )?><script type="text/javascript"> var jArray = <?php echo json_encode($phpArray); ?>; for(var i=0; i<jArray.length; i++){ alert(jArray[i]); } </script>
互换的青春
TA贡献1797条经验 获得超6个赞
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
$employee = array( "employee_id" => 10011, "Name" => "Nathan", "Skills" => array( "analyzing", "documentation" => array( "desktop", "mobile" ) ));
{ "employee_id": 10011, "Name": "Nathan", "Skills": { "0": "analyzing", "documentation": [ "desktop", "mobile" ] }}
$.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: "employee.php", async: false, cache: false, data: { employee_id: 10011 }, success: function (jsonString) { var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array. });
添加回答
举报
0/150
提交
取消