开发者

how we can assign single value of array to any variable in javascript

<?php
$abc=array();
$abc = (abc, cde,fre);
?>
<script language="javascript" type="text/javascript">
for (var i = 0; i < 3; i++) {
v开发者_StackOverflow中文版ar gdf = "<?php echo $lat['i'];?>";
alert("value ="+gdf);
}
</script>


Following your comment, I think this is what you are trying to do:

<?php

$abc = array('abc', 'cde', 'fre');

?>
<script type="text/javascript">
var gdf = '<?php

for ($i = 0; $i < count($abc); $i++) {
    echo "{$abc[$i]}";
    if ($i != (count($abc)-1)) echo ", ";
}

?>';
</script>

Will output:

http://codepad.org/KjEH5CmN

<script type="text/javascript">
var gdf = 'abc, cde, fre';
</script>

NOTE

Using implode if you want a single variable would also work well:

http://codepad.org/UwukCY4m

<?php

$abc = array('abc', 'cde', 'fre');

?>
<script type="text/javascript">
var gdf = '<?php echo implode(', ',$abc); ?>';
</script>


You're not looking to assign a single value of the array; you're looking for the whole array. Your JavaScript loop is trying to iterate over the entire $abc array from PHP.

Something like this would work:

var abc = <?php echo json_encode($abc); ?>;
for(var i = 0; i < 3; i++)
    var gdf = abc[i];
    alert("value = " + gdf);
}


Firstly, to build a PHP array you should be using this notation:

<?php

$abc = array('abc', 'cde', 'fre');

?>

Next, it's not possible use JavaScript to directly loop through your variable that is stored in PHP. You can do something like this instead, performing the loop in PHP:

<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
    <?php foreach ( $abc as $el ): ?>
    alert('value=<?php echo $el ?>');
    <?php endforeach ?>
</script>

Or, if you'd really like the loop to happen in JavaScript and not PHP, you can "export" the PHP array to JavaScript by converting the array to a JSON string and outputting it.

<?php
$abc=array('abc', 'cde', 'fre');
?>
<script language="javascript" type="text/javascript">
    var abc = <?php echo json_encode($abc) ?>;

    for ( var i = 0; i < abc.length; i++ ) {
        alert('value=' + abc[i]);
    }
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜