我试图将一个php关联数组放入Javascript中。我相信这个数组已经被JSON编码了,因为它被插入到一个mongodb中,但是我一直把它作为我的元素未定义到Javascript数组。如果我使用json_encode($ Data),我的javascript元素中没有未定义,但每个元素只有一个字母。 即:myArray [0] = { myArray [1] = M. ...等等。
PHP:
$Data = $_POST['data'];
$Data = json_encode($Data);
echo "<script>var myArray = $Data; </script>";
使用Javascript:
<script>
for(var i=0;i<6;i++){
alert(myArray[i]);
}
</script>
我也试过这样做:
<script>
var myArray = new Array();
'<?php foreach($Data as $key => $val){ ?>'
myArray.push('<?php echo $val; ?>');
'<?php } ?>'
</script>
请帮忙!
更新:来自php数组的var_dump
{ ["Manufacturer"]=> string(5) "Cisco" ["Device_Mdl"]=> string(27) "Cisco"
["Mgmt_Subnets"]=> array(4) { ["Subnet_1"]=> string(7) "Subnet1"
["Subnet_2"]=> string(6) "host 1" ["Subnet_3"]=> string(8) "Subnet 2"
["Subnet_4"]=> string(6) "host 2" } ["Int_Info"]=> array(2) { ["Type"]=>
string(6) "Inband" ["Vlan"]=> string(4) "4092" } ["VLANS"]=> array(2) {
["Int_ID"]=> string(3) "tag" ["Int_Description"]=> string(10) "base" }
["Version"]=> string(0) "" ["MGT_Address"]=> string(11) "103.56.78.6" }