我正在使用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代码段,并将这些数据添加到this.push().中
当我尝试此操作时,总会出现以下错误:未捕获类型错误:无法使用"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.log来查找问题。
谢谢。
这应该会让你朝着正确的方向前进。根据@Pointy,如果你打算在galleria实例上调用push之类的方法,你需要获得对该实例的引用。这只是实现这一点的多种方法之一。基本上,你将galleria示例存储在一个变量中,该变量稍后会传给你的事件处理程序。由于您没有显示要在哪里触发ajax调用/使用新图像更新DOM的事件处理程序,所以我只放了一个模拟处理程序进行演示。
<script type="text/javascript">
function loadImageViaAjax(oEvent) {
$.getJSON(
'/ajax/gallery.ajax.php',
{ command:'load_images' },
function(data) {
oEvent.data.oGalleria.push(data);
});
}
$(document).ready(function(){
var oGalleria = null;
$('#galleria').galleria({
extend: function(options) {
oGalleria = this;
this.push(<?=$add_images;?>);
}
});
$('some selector').click({oGalleria : oGalleria}, loadImageViaAjax);
});
</script>