当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - incrementing a php variable in side a jscript dosent work

问题描述:

<?php

$hello[1]="A";

$hello[2]="B";

$hello[3]="C";

$hello[4]="D";

$m=1;

?>

<html>

<body>

<script>

var i;

<?php $m=1; ?>

for(i=1;i<5;i++)

{

document.write("<?php echo $hello[$m]; ?> <br>");

<?php $m++; ?>

}

</script>

</body>

</html>

in the above php code(file), it only shows the "A" letter for four times. i want it to read all elements in the "hello[]" array. $m doesn't increment by one. i tried "$m=$m+1". it also doesn't work. how can i correct this?

网友答案:

You should loop in php if you want to increase a php variable

<?php
$hello[1]="A";
$hello[2]="B";
$hello[3]="C";
$hello[4]="D";
?>
<html>
<body>
<script>
<?php
for($i=1;$i<5;$i++)
{
?>
    document.write("<?php echo $hello[$i]; ?> <br>");
<?php
}
?>
</script>
</body>
</html>
网友答案:

I'm with Khan Shahrukh on this one, but seeing what you are trying to do, I think you don't really need the JS to print these variables. Maybe this would suit you more:

<html>
<body>
<?php
    $hello[1]="A";
    $hello[2]="B";
    $hello[3]="C";
    $hello[4]="D";

    for($i=1;$i<5;$i++)
    {
        echo $hello[$i] . " <br>";
    }
?>
</body>
</html>

It will output the desired variables directly in the page, instead of using JS (of course, it depends if you actually need it or not).

网友答案:

What about this

<html>
<body>
<?php
    $hello[1]="A";
    $hello[2]="B";
    $hello[3]="C";
    $hello[4]="D";
?>
<script>
<?php
    foreach($hello as $key=>$value)
    {
        echo 'document.write('.$value.');'."\n";
    }
?>
</script>
</body>
</html>

Output:

<html>
<body>
    <script>
        document.write(A);
        document.write(B);
        document.write(C);
        document.write(D);
    </script>
</body>
</html>
分享给朋友:
您可能感兴趣的文章:
随机阅读: