[英]How to pass data from PHP array to Javascript
I'm trying to use the bootstrap-year-calendar and I'm not able to pass the values in the correct way. 我正在尝试使用bootstrap-year-calendar,但无法以正确的方式传递值。
I have an array with the data in this way: 我有这样一种数据数组:
<?php
$data = array(
array(
"startDate" => "2016-1-4",
"endDate" => "2016-1-4"
),
array(
"startDate" => "2016-1-8",
"endDate" => "2016-1-8"
),
array(
"startDate" => "2016-1-16",
"endDate" => "2016-1-16"
)
);
?>
but I have to do something like this: 但我必须做这样的事情:
<?php // I have here my $data array ?>
<div id="calendar"></div>
<script>
$(function() {
$('#calendar').calendar({
dataSource: [
{
startDate: new Date(2016, 1, 4),
endDate: new Date(2016, 1, 4)
},
{
startDate: new Date(2016, 1, 8),
endDate: new Date(2016, 1, 8)
}
,
{
startDate: new Date(2016, 1, 16),
endDate: new Date(2016, 1, 16)
}
]
});
});
</script>
How can I pass my $data array to the 'datasource' variable? 如何将$ data数组传递给'datasource'变量?
Use json: 使用json:
Do something like 做类似的事情
<?php
$data = array(
array(
"startDate" => "2016-1-4",
"endDate" => "2016-1-4"
),
array(
"startDate" => "2016-1-8",
"endDate" => "2016-1-8"
),
array(
"startDate" => "2016-1-16",
"endDate" => "2016-1-16"
)
);
echo '<script>var data = '.json_encode($data).'</script>';
?>
<script>
$.each(data, function(i, v) {
$.each(v, function(x, t) {
data[i][x] = new Date(t);
});
});
$(function() {
$('#calendar').calendar({
dataSource: JSON.parse(data)
});
});
</script>
Ps: you may need to joggle a bit with the dates 附:您可能需要稍微调整一下日期
demo: http://jsfiddle.net/jnp2ssts/1/ 演示: http : //jsfiddle.net/jnp2ssts/1/
You can do something like while page is loading (if it's a PHP page) or if data is received using AJAX 您可以执行类似页面加载时(如果是PHP页面)或使用AJAX接收数据的操作
var data = <?php echo json_encode($data); ?>;
then simply use this variable with datasource as 然后只需将此变量与数据源一起使用
dataSource : data
Final code will look like something like 最终代码看起来像
var data = <?php echo json_encode($data); ?>;
$(function() {
$('#calendar').calendar({
dataSource: data
});
});
Yes, you can use json_encode()
是的,您可以使用
json_encode()
<---Your array in php--->
<script type="text/javascript">
var jArray= <?php echo json_encode($phpArray ); ?>;
for(var<your loop>){
alert(jArray[i]);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.