Reputation: 2783
Below is my code where the php array $keys assigned to a JS array var keysArr, But the value display on the alert box is not correct.
Thus, there is something wrong on assign Php array to Js array.
Can anyone help me? Thanks in advance!
<?php
$keys = array(1, 2, 3, 4);
?>
<html>
<head>
<script type="text/javascript">
var keysArr = <?php print $keys?>;
for (var i = 0; i < keysArr.length; ++i){
alert(keysArr[i]);
}
</script>
</head>
<body>
</body>
</html>
Upvotes: 3
Views: 179
Reputation: 39
<?php
$keys = array(1, 2, 3, 4);
?>
<html>
<head>
<script type="text/javascript">
var keysArr = Array(<?php foreach($keys as $key) echo (is_numeric($key))? $key : '"'.$key.'"' ;?>);
for (var i = 0; i < keysArr.length; ++i){
alert(keysArr[i]);
}
</script>
</head>
<body>
</body>
</html>
Try this... I haven't tested it yet, but it would print numbers without quotes (") and other stuff with them.
Upvotes: 1
Reputation: 1828
Try this
<?php
$keys = array(1, 2, 3, 4);
?>
<html>
<head>
<script type="text/javascript">
var keysArr = Array(<?php echo implode(',',$keys);?>);
for (var i = 0; i < keysArr.length; ++i){
alert(keysArr[i]);
}
</script>
</head>
<body>
</body>
</html>
whith print you're just showing Array
, and not proper array code for js. Look inside the HTML you generate.
Upvotes: 0
Reputation: 3341
Try this, it doesn't need JSON extension:
var keysArr = [ <?php print implode(',', $keys); ?> ];
for (var i = 0; i < keysArr.length; ++i){
alert(keysArr[i]);
}
Upvotes: 1
Reputation: 43168
var keysArr = <?php json_encode($keys) ?>;
requires PHP >= 5.2.0, but third-party json_encode() implementations are available for older versions.
Upvotes: 9