2012-11-14 221 views
0

我想預加載一個包含圖像的目錄。預加載圖像目錄

到目前爲止我使用這段代碼:

preload.php

<?php 
function listImages($dir){ 
    $ffs = scandir($dir); 
    foreach($ffs as $ff){ 
     if($ff != '.' && $ff != '..' && strstr($ff, '.png') || strstr($ff, '.jpg') || strstr($ff, '.gif') || strstr($ff, '.jpeg')){ 
      echo '"images/'.$ff; 
      if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff); 
      echo '", '; 
     } 
    } 
} 
echo '[ '; 
listImages('images'); 
echo ']'; 
// output: ["image1.png", "image2.png"] etc. 
?> 

footer.php

<script type="text/javascript"> 
    // put contents of all_images.php file into variable 'images' 

$.ajax({ 
    type: "GET", 
    async: false, 
    cache: false, 
    url: "./preload.php", 
    data: "getid=true", 
    success: function(data){ 
    images=data; 
    } 
}); 

    // The variable 'images' now contains string of file names 
    // needed to be preloaded. 
    $.fn.preload = function() { 
     this.each(function(){ 
      $('<img/>')[0].src = this; 
     }); 
    } 


</script> 


<script type="text/javascript"> 
$(document).ready(function(){ 
$(images).preload(); 
</script> 

但它似乎沒有工作。在螢火蟲我得到uncaught exception: Syntax error, unrecognized expression:

如果我貼我所有的鏈接,而不是的「圖像」 $(images).preload(); 我does`nt得到一個錯誤,但也不會加載我的圖片。

任何幫助表示讚賞,因爲即時坐在這裏整整一天試圖弄清楚。

更新#1

所以,現在即時通訊做這樣的:

$(document).ready(function(){ 
    $.getJSON("./preload.php?getid=true", function(data) { 
    var images = []; 
    $.each(data, function(i, val) { 
     images[i] = new Image().src=val;` 

     $.fn.preload = function() { 
      this.each(function(){ 
       $('<img/>')[0].src = this; 
      }); 
     } 
     $(images).preload(); 
    }); 
    }); 
}); 

沒有錯誤爲止,但圖像仍然沒有在Firebug的「網絡」選項卡中顯示。

+1

運行它通過[JSON編碼器(http://php.net/manual/en/function.json-encode.php),並使用JSON來得到它。 – mplungjan

+0

嘗試將'dataType:'json''添加到您的AJAX設置中。 – Korikulum

+0

with dataType''json'我得到'ReferenceError:images is not defined' – fourgood

回答

3

幾個問題

嘗試getJSON

$(document).ready(function(){ 
    $.getJSON("./preload.php?getid=true", function(data) { 
    var images = []; 
    $.each(data, function(i, val) { 
     images[i] = new Image().src=val; 
    }); 
    }); 
}); 
+0

與此我得到:'ReferenceError:圖像未定義' – fourgood

+0

看到更新。您的document.ready也是錯誤的 – mplungjan