2015-11-06 60 views
1

我是JavaScript新手,我試圖將數據庫中的圖像傳遞到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> 
+0

如果我沒有記錯的話,你正在使用笨,需要知道什麼是錯誤說... –

+1

codeigniter它可以。但通過圖像轉換爲JavaScript我不能 – user307709

+2

@MarmikBhatt你沒有錯。 'codeigniter'標籤將其送走.. – MaggsWeb

回答

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> 
+0

它是我的工作感謝兄弟.very謝謝q:D – user307709

+0

我唯一擔心的是,從數組MIGHT中選擇的隨機數有時會太高,導致錯誤。看看編輯/修改後的版本。 – RamRaider

+0

in var path ='。/ images/burger /';「; – user307709

2

你需要創建一個javascriptarraypush圖像路徑。

之前<?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> 

循環後...

<script> 
    randImg(images); 
</script> 
+0

謝謝q幫助 – user307709

相關問題