如何把PHP的二维数组赋值给JS变量

JavaScript027

如何把PHP的二维数组赋值给JS变量,第1张

<script>

a = new array()

<?php

$array = array("a" =>array(1,2),

"b" =>array(3,4)

)

foreach($array as $K=>$V)

{

echo "a[$K] = new array()"

foreach($V as $k=>$v)

{

echo "a[$K][$k] = $v"

}

}

?>

</script>

把对象数组转成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对象