dtzh131555 2014-11-26 01:57
浏览 29

在通过JSON传递给JavaScript之前声明PHP的位置?

Well, I can successfully fetch a result set from a MySQL database via PHP, and display its contents on a web page via HTML.

I can also write JavaScript functions.

Here's the problem: I have no idea where, physically, I need to put my PHP code to have the array result set show up in my JavaScript functions!

Here's my PHP:

<?php

    $photos = array();
    [code to fill this array with results from database]

?>

I have this directly under the head. Also under the head:

<script>

    prevPhoto() {

        var jPhotoArray = <?php echo json_encode($photos); ?>;

        for (var i = 0; i < jPhotoArray.length; i++){

            if (thePhoto.src == jPhotoArray[i]['photo']) {

                if (i + 1 != jPhotoArray.length) {

                    thePhoto.src = jPhotoArray[i + 1]['photo'];

                }

            }

        }

    }

</script>

(For the curious, the intended functionality is to create a manual slideshow of photos that users can flip through by clicking "forward" and "backward" for as long as there is another picture behind the one currently displayed.)

But when I launch the page and take a look at the memory, the variable jPhotoArray is null.

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • dougui1977 2014-11-26 02:02
    关注

    PHP doesn't know or care where it exists when mixed with output. All that happens is PHP is executed, then anything not in a PHP block is sent to the output buffer, then more PHP is executed if there is another PHP block.

    In your case, all you need to do is put data in your $photos array before you get down to your <script> tag.

    If it isn't working, something else is wrong. Use var_dump() to ensure that $photos has anything in it first. Chances are, your problem is elsewhere in your code. Also, always view the source of your HTML to see what that assignment line actually has in the output.

    Finally, as a matter of code style, it is best to get all of your application logic done before you output anything at all. Separate the concept of the view, outside of that application logic.

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b