如何将php数组的值传递给javascript数组?

JavaScript017

如何将php数组的值传递给javascript数组?,第1张

把对象数组转成JASON串,PHP收到后转化成JASON对象进行读取。

参考例子如下:

<script type="text/javascript" src="http://www.coding123.net/rardownload/20110420/20110420113851756.js"></script><!--倒入json.js文件,序列化json对象用的-->

<script type="text/javascript" src="http://www.coding123.net/js/jquery.js"></script>

<script type="text/javascript">

var zNodes =[

{ id:1, pId:0, name:"随意勾选 1", open:true},

{ id:11, pId:1, name:"随意勾选 1-1", open:true},

{ id:111, pId:11, name:"随意勾选 1-1-1"},

{ id:112, pId:11, name:"随意勾选 1-1-2"},

{ id:12, pId:1, name:"随意勾选 1-2", open:true},

{ id:121, pId:12, name:"随意勾选 1-2-1"},

{ id:122, pId:12, name:"随意勾选 1-2-2"},

{ id:2, pId:0, name:"随意勾选 2", checked:true, open:true},

{ id:21, pId:2, name:"随意勾选 2-1"},

{ id:22, pId:2, name:"随意勾选 2-2", open:true},

{ id:221, pId:22, name:"随意勾选 2-2-1", checked:true},

{ id:222, pId:22, name:"随意勾选 2-2-2"},

{ id:23, pId:2, name:"随意勾选 2-3"}

]

$.ajax({

url:'xxxx.php'//改为你的动态页

,type:'POST'

,data:{zNodes:zNodes.toJSONString()}//调用json.js类库将json对象转换为对应的JSON结构字符串

,success:function(rst){alert('PHP接收JSON数据成功!')}

,error:function(xhr){alert('PHP页面有错误!'+xhr.responseText)}

}})

</script>

$zNodes=$_POST["zNodes"]

$json=json_decode($zNodes)//转化为JSON对象

php中的数组转换成json格式,然后输出到页面中.

<script type='text/javascript'>

var arr = <?php echo $json?>

</script>

var addbgm =new Array()<?php

foreach($dellieb as $value){

echo "addbgm[addbgm.length]=".$value

}

?>