我正在使用 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 示例完全相同。我通过回显与上面相同的 PHP 代码段来尝试 $.get,并将此数据添加到 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.logs 来追踪问题。
谢谢。
最佳答案
这会让您朝着正确的方向前进。 Per @Pointy 如果您打算调用类似 push 的方法,则需要获取对 gallery 实例的引用。这只是众多方法中的一种。基本上,您将 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>
关于php - this.push() 适用于 PHP 数据但不适用于 javascript 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8949045/