【发布时间】:2012-01-20 23:12:40
【问题描述】:
我正在使用 Galleria,它允许您使用 this.push({ image:'image.jpg' }) 动态添加图像
奇怪的是,当我使用 PHP 编写代码时,它运行良好:
<?php
while {
$add_images .= '{
thumb:'".$thumb."',
image:'".$image."'
}';
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('#galleria').galleria({
extend: function(options) {
this.push(<?=$add_images;?>);
}
})
});
</script>
这行得通。但是,我想使用 AJAX 加载新图像:
$.getJSON('/ajax/gallery.ajax.php', { command:'load_images' }, function(data){
this.push(data);
}
回调数据的格式与前面的 PHP 示例完全相同。我尝试 $.get 通过回显与上面相同的 PHP sn-p 并将此数据添加到 this.push() 中。
当我尝试这个时,我总是得到这个错误: 未捕获的 TypeError:无法使用 'in' 运算符搜索 'thumb'
Uncaught TypeError: Cannot use 'in' operator to search for 'thumb' in {
thumb:'/images/gallerij/1/vanderkam-fvhd5wq1jy-t.jpg',
image:'/images/gallerij/1/vanderkam-fvhd5wq1jy.jpg',
big:'/images/gallerij/1/vanderkam-fvhd5wq1jy.jpg',
title:' image []', description:'null'
},{
thumb:'/images/gallerij/1/vanderkam-oguuob7pyd-t.jpg',
image:'/images/gallerij/1/vanderkam-oguuob7pyd.jpg',
big:'/images/gallerij/1/vanderkam-oguuob7pyd.jpg',
title:' image []', description:'null'
}
在将回调数据传回对象时也可以使用。但是,为此,我不知道如何使它适用于多个图像:
// code shortened to make it better readable
$.getJSON('/ajax/gallery.ajax.php', { command:'load_images' }, function(data){
var images;
$.each(data, function(entryIndex, entry){
images = { thumb:entry.thumb, image:entry.image, big:entry.big, title:entry.title, description:entry.description };
$galleria.push(images);
}
}
如您所见,图像现在被推送到每个循环中,导致性能不佳。如何使用 AJAX 推送图片?数据格式必须如下:
{ image:'image1.jpg' }, { image:'image2.jpg'}, { image:'image3.jpg'}
//Sending data directly to this.push() using json_encode() using PHP
//will add brackets to the output like this:
[{ image:'image1.jpg' }, { image:'image2.jpg'}, { image:'image3.jpg'}]
//This however will not work
如果我直接复制/粘贴回调数据,它也可以工作,但通过 javascript 加载我会再次收到该错误。
http://galleria.io/docs/1.2/api/methods/#push-element1-elementn
实际站点: http://www.vanderkamfashion.nl/
请向下滚动查看图库。它 - 应该 - 当第 25 张照片被点击或最后一个缩略图被点击(第 31 张)时加载新图像。我运行了一些 console.logs 来追踪问题。
谢谢。
【问题讨论】:
-
您希望
this在您的.getJSON()回调中绑定到什么?它肯定不会是画廊对象。 -
我知道,我删除了一些代码以使其更具可读性。 getJSON 是 $('#galleria').galleria({ extend: function(options) {} }); 的一部分
-
好吧,不管代码在哪里,
this都会被浏览器设置,不会是外部上下文中的this。
标签: php javascript galleria