我想预加载一个包含图像的目录。预加载图像目录
到目前为止我使用这段代码:
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的“网络”选项卡中显示。
运行它通过[JSON编码器(http://php.net/manual/en/function.json-encode.php),并使用JSON来得到它。 – mplungjan
尝试将'dataType:'json''添加到您的AJAX设置中。 – Korikulum
with dataType''json'我得到'ReferenceError:images is not defined' – fourgood