如何将图像从数据库传递到javascript?

时间:2015-11-06 08:40:17

标签: javascript php jquery codeigniter-3

我是javascript的新手,我正试图将图像从数据库传递到javascript中,但我不能。

问题代码是:

'<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';

这是我的代码

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div id="box">
    <img id="image" />
</div>
<?php
$query = $this->db->get('product');
foreach($query->result() as $val):
?>

<script>

    var images =
    '<img src="<?php echo base_url().'./images/burger/'.$val->image ?>">';

function randImg() {
    var size = images.length
    var x = Math.floor(size * Math.random())
    document.getElementById('image').src = images[x];
}

randImg();
</script>
<?php endforeach; ?>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您需要在leftbuttoninv.onEnterFrame = function() { if(your_object){ if (Key.isDown(Key.LEFT)) { rotation_answer=answer_left; gotoAndPlay(2); } else if (Key.isDown(Key.RIGHT)) { rotation_answer=answer_right; gotoAndPlay(2); } } } array图像路径中创建javascript

push之前

<?php foreach(...

在循环内..

<script>
    var images = [];
    function randImg(images) {
        var size = images.length
        var x = Math.floor(size * Math.random())
        document.getElementById('image').src = images[x];
    }
</script>

循环后......

<script>
    images.push("<?php echo base_url().'./images/burger/'.$val->image ?>");
</script>

答案 1 :(得分:2)

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript random image</title>
        <?php
            /* Query the db */
            $query = $this->db->get('product');
            /* use php to generate the javascript array of images from db query */
            echo "
            <script type='text/javascript'>
                var images=[];
                var baseurl='".base_url()."';
                var path='./images/burger/';";

            foreach( $query->result() as $val ){
                /* Add image to javascript array */
                echo "images.push('{$val->image}');\n";
            }

            echo "
            </script>";
        ?>  
        <script type='text/javascript'>

            function rnd_index(a,b) {
                return Math.round( a + ( Math.random() * ( b - a ) ) );
            }
            function randImg() {
                var x = rnd_index( 0, images.length-1 );
                document.getElementById('image').src = baseurl + path + images[ x ];
            }

            function orig__randImg() {
                var size = images.length;/* This might be too large sometimes for the array */
                var x = Math.floor( size * Math.random() );
                document.getElementById('image').src = path + images[ x ];
            }
            /* Load a random image when the page has loaded */
            window.onload=randImg;
        </script>
    </head>
    <body>
        <div id="box">
            <img id="image" />
        </div>
    </body>
</html>